一、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/n/219849.html