pdf转ppt-fat ntfs

2023年4月2日发(作者:远程路由器)
Python判断⽂件和⽂件夹是否存在的⽅法
⼀、python判断⽂件和⽂件夹是否存在、创建⽂件夹
复制代码代码如下:
>>>importos
>>>('d:/assist')
True
>>>('d:/assist/')
True
>>>('d:/assist')
False
>>>('d:/assist/')
True
>>>rs('d:/assist/set')
>>>('d:/assist/set')
True
⼆、python判断⽂件是否存在
复制代码代码如下:
importos
filename=r'/home/tim/workspace/'
(filename):
message='OK,the"%s"fileexists.'
else:
message="Sorry,Icannotfindthe"%s"file."
printmessage%filename
三、如何⽤Python判断⽂件是否存在
使⽤()⽅法可以直接判断⽂件是否存在。
代码如下:
复制代码代码如下:
>>>importos
>>>(r'C:')
False
>>>
如果存在返回值为True,如果不存在则返回False
四、python判断⽂件夹是否存在
复制代码代码如下:
$python
Python2.7.3(default,Jan22013,16:53:07)
[GCC4.7.2]onlinux2
Type"help","copyright","credits"or"license"formoreinformation.
>>>importos
>>>
>>>
>>>tobecheckdir=r'/home/tim/workspace'
>>>(tobecheckdir)
True
>>>
五、python检查⽂件是否存在,以及路径是否为⽂件
在写⽂件之前通常需要检查⽂件路径是否可写:
复制代码代码如下:
fromosimportpath,access,R_OK#W_OKforwritepermission.
PATH='./'
(PATH)(PATH)andaccess(PATH,R_OK):
print"Fileexistsandisreadable"
else:
print"Eitherfileismissingorisnotreadable"
你也可以通过下⾯的⽅式实现:
复制代码代码如下:
deffile_exists(filename):
try:
withopen(filename)asf:
returnTrue
exceptIOError:
returnFalse
六、python判断⽂件和⽂件夹是否存在
复制代码代码如下:
importos
('')#如果不存在就返回False
(directory)#如果⽬录不存在就返回False
七、
还有s(path)
对broken的linkfile也返回True.
⼋、pythonFTP判断⽂件夹是否存在
python怎样判断⽂件夹是否存在?⼴⼤⽹友给出了答案:
使⽤ftp库就可以了,下⾯是Python核⼼编程上的例⼦:
复制代码代码如下:
>>>fromftplibimportFTP
>>>f=FTP('')
>>>('anonymous','guido@')
'230Guestloginok,accessrestrictionsapply.'
>>>()
dir结果中⽆此⽂件,就是不存在。
或者如下:
复制代码代码如下:
try:
nary('RETR%s'%FILE,open(FILE,'wb').write)
_perm:
print'ERROR:cannotreadfile"%s"'%(FILE)
不能读此⽂件,也视为不存在。
更多推荐
pathfileexists
发布评论