程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

There are three ways to determine whether a file exists in Python

編輯:Python

Usually before reading and writing files , You need to judge whether the file or directory exists , Otherwise, some processing methods may make the program error . So it's best to do anything before , First, judge whether the file exists .

Here are three ways to determine whether a file or folder exists , Separate use os modular 、Try sentence 、pathlib modular .

1. Use os modular

os Module os.path.exists() Method is used to verify the existence of a file .

  • Judge whether the file exists
import os
os.path.exists(test_file.txt)
#True
os.path.exists(no_exist_file.txt)
#False
  • Determine whether the folder exists
import os
os.path.exists(test_dir)
#True
os.path.exists(no_exist_dir)
#False

It can be seen that os.path.exists() Method , Judge whether files and folders are the same .

In fact, there is still a problem with this method , Suppose you want to check the file “test_data” Whether there is , But there is a name under the current path “test_data” Folder , In this way, misjudgment may occur . To avoid such a situation , It can be like this :

  • Check only files
import os
os.path.isfile("test-data")

Through this method , If the file ”test-data” Does not exist, will return False, Instead, return to True.

That is, the file exists , You may also need to determine whether the file can be read and written .

Judge whether the file can be read or written

Use os.access() Method to determine whether the file can be read and written .

grammar :

os.access(path, mode)

path Is the file path ,mode Is the operation mode , There are so many :

  • os.F_OK: Check if the file exists ;

  • os.R_OK: Check that the file is readable ;

  • os.W_OK: Check whether the file can be written ;

  • os.X_OK: Check if the file can be executed

This method returns by judging whether the file path exists and the permissions of various access modes True perhaps False.

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")

2. Use Try sentence

It can be used directly in the program open() Method to check whether the file exists and can be read and written .

grammar :

open()

If you open The file for does not exist , The program will throw an error , Use try Statement to catch this error .

The program cannot access the file , There may be many reasons :

  • If you open The file for does not exist , Will throw a FileNotFoundError It's abnormal ;

  • File exists , But you don't have access to , Will throw out a PersmissionError It's abnormal .

So you can use the following code to determine whether the file exists :

try:
f =open()
f.close()
except FileNotFoundError:
print ("File is not found.")
except PermissionError:
print ("You don't have permission to access this file.")

In fact, there is no need to deal with every exception so carefully , The above two exceptions are IOError Subclasses of . So you can simplify the program :

'''
No one answers the problems encountered in learning ? Xiaobian created a Python Learning exchange group :153708845
Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book !
'''
try:
f =open()
f.close()
except IOError:
print ("File is not accessible.")

Use try Sentence to judge , Handling all exceptions is very simple and elegant . And compared with others, there is no need to introduce other external modules .

3. Use pathlib modular

pathlib Modules in Python3 In the version, there are built-in modules , But in Python2 Third party modules need to be installed separately .

Use pathlib You need to use the file path to create path object . This path can be a file name or directory path .

  • Check if the path exists
path = pathlib.Path("path/file")
path.exist()
  • Check if the path is a file
path = pathlib.Path("path/file")
path.is_file()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved