好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python中使用三种方法判断文件或文件夹是否存在的实例分享

本文给大家介绍三种判断文件或文件夹是否存在的方法,分别使用os模块、Try语句、pathlib模块。感兴趣的朋友一起看看吧

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 
import os
os.path.isfile("test-data") 
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" 
try:
  f =open()
  f.close()
except FileNotFoundError:
  print "File is not found."
except PersmissionError:
  print "You don't have permission to access this file." 
try:
  f =open()
  f.close()
except IOError:
  print "File is not accessible." 
path = pathlib.Path("path/file")
path.exist() 
path = pathlib.Path("path/file")
path.is_file() 

总结

以上就是Python中使用三种方法判断文件或文件夹是否存在的实例分享的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于Python中使用三种方法判断文件或文件夹是否存在的实例分享的详细内容...

  阅读:41次