判断文件是否存在
判断文件或文件夹是否存在的方法,分别使用os模块、pathlib模块
1、os模块
os模块中的os.path.exists()方法用于检验文件是否存在。
import os os.path.exists(test_file.txt) #True os.path.exists(no_exist_file.txt) #False
- 判断文件夹是否存在
import os os.path.exists(test_dir) #True os.path.exists(no_exist_dir) #False
检查文件“test_data”是否存在,但是当前路径下有个叫“test_data”的文件夹,这样就可能出现误判。为了避免这样的情况,只检查文件
import os os.path.isfile("test-data")
如果文件”test-data”不存在将返回False,反之返回True。文件存在,可能还需要判断文件是否可进行读写操作
判断文件是否可做读写操作
使用os.access()方法判断文件是否可进行读写操作。
os.access(path, mode)
path为文件路径,mode为操作模式,有这么几种:
-
os.F_OK: 检查文件是否存在;
-
os.R_OK: 检查文件是否可读;
-
os.W_OK: 检查文件是否可以写入;
-
os.X_OK: 检查文件是否可以执行
import os if os.access("/file/path/foo.txt", os.F_OK): print "Given file path is exist." if os.access("/file/path/foo.txt", os.R_OK): print "File is accessible to read" if os.access("/file/path/foo.txt", os.W_OK): print "File is accessible to write" if os.access("/file/path/foo.txt", os.X_OK): print "File is accessible to execute"
使用pathlib模块
使用pathlib需要先使用文件路径来创建path对象。此路径可以是文件名或目录路径。
- 检查路径是否存在
path = pathlib.Path("path/file") path.exist()
- 检查路径是否是文件
path = pathlib.Path("path/file") path.is_file()
立志如山 静心求实
浙公网安备 33010602011771号