一、os.path.exists函數簡介
os.path.exists函數是Python中非常常用的一個函數,它用於判斷指定的文件或目錄是否存在。當文件或目錄存在時,該函數返回True;否則返回False。
import os
path = "/path/to/file"
if os.path.exists(path):
print("file or directory exists")
else:
print("file or directory does not exist")
二、判斷文件是否存在
os.path.exists函數可以用於判斷指定的文件是否存在。下面是一個示例:
import os
file_path = "/path/to/file"
if os.path.exists(file_path):
print("file exists")
else:
print("file does not exist")
需要注意的是,判斷文件是否存在時,文件名需要包括完整的路徑。
三、判斷目錄是否存在
os.path.exists函數也可以用於判斷指定的目錄是否存在。下面是一個示例:
import os
dir_path = "/path/to/dir"
if os.path.exists(dir_path):
print("directory exists")
else:
print("directory does not exist")
需要注意的是,這裡的dir_path也需要包括完整的路徑。
四、其他常見應用場景
os.path.exists函數還可以用於以下幾個常見應用場景:
1. 判斷文件夾內是否有某個文件
可以利用os.path.join函數組合出文件和文件所在目錄的路徑,判斷該路徑是否存在:
import os
dir_path = "/path/to/dir"
file_name = "test.txt"
file_path = os.path.join(dir_path, file_name)
if os.path.exists(file_path):
print("file exists in directory")
else:
print("file does not exist in directory")
2. 刪除文件或目錄
在刪除文件或目錄之前,可以先使用os.path.exists函數判斷文件或目錄是否存在。
例如,刪除某個文件:
import os
file_path = "/path/to/file"
if os.path.exists(file_path):
os.remove(file_path)
print("file removed")
else:
print("file does not exist")
再例如,遞歸刪除某個目錄及其子目錄中的所有文件和文件夾:
import os
dir_path = "/path/to/dir"
if os.path.exists(dir_path):
for root, dirs, files in os.walk(dir_path, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(dir_path)
print("directory and all its contents removed")
else:
print("directory does not exist")
3. 複製文件或目錄
在複製文件或目錄之前,可以先使用os.path.exists函數判斷源文件或目錄是否存在。
例如,複製某個文件:
import os
import shutil
src_file_path = "/path/to/src_file"
dst_file_path = "/path/to/dst_file"
if os.path.exists(src_file_path):
shutil.copy(src_file_path, dst_file_path)
print("file copied")
else:
print("source file does not exist")
再例如,遞歸複製某個目錄及其子目錄中的所有文件和文件夾:
import os
import shutil
src_dir_path = "/path/to/src_dir"
dst_dir_path = "/path/to/dst_dir"
if os.path.exists(src_dir_path):
shutil.copytree(src_dir_path, dst_dir_path)
print("directory and all its contents copied")
else:
print("source directory does not exist")
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/219849.html