exists()函数如何检查文件是否存在?”
发布时间:2023-06-30 18:36:07
exists()函数是Python中os模块中的一个方法,用于检查指定路径下的文件或文件夹是否存在。
函数原型:os.path.exists(path)
参数path为要检查的路径字符串。
返回值为布尔值,如果路径存在则返回True,否则返回False。
使用exists()函数可以方便地检查文件或文件夹是否存在,可以避免在文件操作时出现找不到文件的错误。
下面是一些使用exists()函数的示例:
1. 检查文件是否存在:
import os
file_path = 'path/to/file.txt'
if os.path.exists(file_path):
print('文件存在')
else:
print('文件不存在')
2. 检查文件夹是否存在:
import os
dir_path = 'path/to/directory'
if os.path.exists(dir_path):
print('文件夹存在')
else:
print('文件夹不存在')
3. 检查文件或文件夹是否存在,并进行相应的操作:
import os
path = 'path/to/file_or_directory'
if os.path.exists(path):
if os.path.isfile(path):
print('路径为文件')
# 进行文件相关的操作
elif os.path.isdir(path):
print('路径为文件夹')
# 进行文件夹相关的操作
else:
print('路径不存在')
需要注意的是,exists()函数只能检查指定路径下的文件或文件夹是否存在,不能检查文件是否可读、可写等权限相关的信息。如果需要检查这些信息,可以使用其他函数如os.access()等。
综上所述,exists()函数能够方便地检查文件或文件夹是否存在,帮助我们避免出现找不到文件的错误。
