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"
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短