Python判断文件和文件夹是否存在的方法
一、python判断文件和文件夹是否存在、创建文件夹
>>>importos >>>os.path.exists('d:/assist') True >>>os.path.exists('d:/assist/getTeacherList.py') True >>>os.path.isfile('d:/assist') False >>>os.path.isfile('d:/assist/getTeacherList.py') True >>>os.makedirs('d:/assist/set') >>>os.path.exists('d:/assist/set') True
二、python判断文件是否存在
importos filename=r'/home/tim/workspace/test.txt' ifos.path.exists(filename): message='OK,the"%s"fileexists.' else: message="Sorry,Icannotfindthe"%s"file." printmessage%filename
三、如何用Python判断文件是否存在
使用os.path.exists()方法可以直接判断文件是否存在。
代码如下:
>>>importos >>>os.path.exists(r'C:\1.TXT') False >>>
如果存在返回值为True,如果不存在则返回False
四、python判断文件夹是否存在
$python Python2.7.3(default,Jan 22013,16:53:07) [GCC4.7.2]onlinux2 Type"help","copyright","credits"or"license"formoreinformation. >>>importos >>> >>> >>>tobecheckdir=r'/home/tim/workspace' >>>os.path.isdir(tobecheckdir) True >>>
五、python检查文件是否存在,以及路径是否为文件
在写文件之前通常需要检查文件路径是否可写:
fromosimportpath,access,R_OK #W_OKforwritepermission.
PATH='./file.txt'
ifpath.exists(PATH)andpath.isfile(PATH)andaccess(PATH,R_OK): print"Fileexistsandisreadable" else: print"Eitherfileismissingorisnotreadable"