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

Several methods of judging files by Python and their advantages and disadvantages

編輯:Python

Catalog

Preface

Lazy try sentence

Conventional os modular

Fashionable pathlib modular

Comparison of advantages and disadvantages of several methods

summary

Preface

We know that when the file does not exist ,open() Both the write mode and the append mode of the method create new files , But there are many scenarios for judging files , such as , When the crawler downloads pictures , It may be necessary to determine whether the file exists , Avoid repeated Downloads ; And such as , When creating a new file , It may be necessary to determine whether the file exists , Make a backup if it exists …… therefore , Learn to judge whether the file exists , It's necessary .

Learning is a gradual process , If the connection between knowledge points can be established , To learn systematically , That will help the effect . Read this article , You will read the following :

1、 How to judge the file (try sentence 、os modular 、pathlib modular )
2、 The advantages and disadvantages of the above methods are compared

Lazy try sentence

We have learned before , Use with Statement to handle file reading and writing , but with Statements are not omnipotent , So we have to pay attention to some abnormal situations .

for example , When using open() Method time , If the file doesn't exist , The program will throw FileNotFoundError abnormal , And if the permission is insufficient , Will throw PersmissionError abnormal .

with open("python.log", "r") as f: ...: f.read()-----------------------...( A little )FileNotFoundError: [Errno 2] No such file or directory: 'python.log'

To avoid these exceptions leading to program interruption , We can use try…except… Statement to catch exceptions , And then in except Clause to handle exceptions .

however , In the eyes of the cat , This method is not recommended . There are two reasons , First, this method is very passive , The health of the program is subject to unpredictable anomalies ; Second, when the file does not exist , We may need to create a file , If these logics are written in except In Clause , Poor readability .

Conventional os modular

seeing the name of a thing one thinks of its function ,Python Built in os Modules are used to communicate with OS( operating system ) Interactive module , It can perform many operations on the command line , for example , Get operating system information 、 obtain / Modify environment variables 、 Perform directory operations ( establish 、 Delete 、 Traverse ) And various file operations . below , We need to learn several methods closely related to file judgment .

1、os.path.exists() Used to determine whether files and folders exist ( Be careful : Because both can judge , To effectively distinguish between files and folders , It is best to ensure that the file name is suffixed ):

import os# File exists VS non-existent os.path.exists("test.txt") >>>Trueos.path.exists("cat.txt") >>>False# Folder exists VS non-existent os.path.exists("cat/images") >>>Trueos.path.exists("cat/image") >>>False

2、os.path.isfile()、os.path.isdir() Determine whether the given path is a file or a folder :

os.path.isfile("cat/images") >>>Falseos.path.isdir("cat/images") >>>Trueos.path.isfile("test.txt") >>>True

3、os.access() Check the access rights of the file path , grammar :os.access(path, mode); among path Refers to a file or folder ,mode It refers to the mode to be detected :

os.access("cat/images", os.F_OK) >>>True # path There is os.access("cat/images", os.R_OK) >>>True # path Can be read os.access("cat/images", os.W_OK) >>>True # path Can write os.access("cat/images", os.X_OK) >>>True # path Executable

4、os Other common methods in the module :

os.mkdir() Create directory 、os.rmdir() Delete directory 、os.rename() rename 、os.remove() Delete file 、os.path.join() Connect directory and filename 、os.path.split() Split directory and file name ……( Not one by one , I will have the opportunity to make another introduction in the future )

Fashionable pathlib modular

pathlib The module is python3.4 Just added modules , Officially, it is an object-oriented file system path (Object-oriented filesystem paths), This is a very powerful module , The official document address is attached at the end of the text .

Here are some basic usages :

import pathlibfile_obj = pathlib.Path("test.txt")file_obj.name >>>'test.txt' # file name file_obj.exists() >>> True # Whether there is file_obj.is_dir() >>>False # Do you want to create a folder file_obj.is_file() >>>True # Is it a document Comparison of advantages and disadvantages of several methods

There is a lot of knowledge about file operation , Limited to space , This paper mainly introduces the judgment file , In the future, we may learn other specific topics .

Now you know several ways to determine whether a file exists , Cats and cats try to follow their own understanding , Judge them .

First ,try The disadvantage of the statement is that it does not take the initiative to make a judgment , It is not convenient to make targeted treatment according to whether the file exists , It gives the necessary logic to exception catchers , More or less “ be irresponsible for ”;try Statements also have advantages , First, there is no need to introduce modules , There is no need to distinguish between various methods of use , The second is to package other possible exceptions , Avoid the omission of multiple systems or scenarios .

os Module is a traditional old module , It will be smooth in use and maintenance ; Its main drawback is that some methods are cumbersome , For example, the use of strings to represent file paths , This will cause trouble in path splicing . in addition , Differences in path delimiters between different operating systems (Windows Use \ Separator ,Linux and Mac Use / Separator ), It may also lead to errors that are difficult to find .

relatively speaking ,pathlib Most powerful , But the popularity is relatively low , There is a certain threshold for learning ; Its main advantage is object orientation , meanwhile , Because the characteristics of different operating systems are encapsulated , It can effectively avoid the problem of string representing file path . It also has shortcomings , That is, there is no such thing as os.access() This method can detect access rights , Although this method will not be used .

The following compares three methods of splicing file paths , Method 1 does not handle delimiters , There is no guarantee that it will be found on every operating system ; Method 2 needs to be used repeatedly os.path.join; Method 3 uses only “/" You can splice paths , And it definitely supports multiple operating systems .

# Wrong splicing : Unhandled delimiter data_folder = "source_data/text_files/"file_to_open = data_folder + "test.txt"# os Module splicing import osdata_folder = os.path.join("source_data", "text_files")file_to_open = os.path.join(data_folder, "test.txt")# pathlib Module splicing from pathlib import Pathdata_folder = Path("source_data/text_files/")file_to_open = data_folder / "test.txt"

To sum up , If the file path is simple , Just use exists()、is_dir()、is_file() These methods ,os.path Module and pathlib.Path Modules are equal , They all work well , But if you consider the complicated path splicing ,pathlib.Path You will win .

summary

This is about using Python This is the end of the article on several methods for judging documents and their advantages and disadvantages , More about Python To judge the contents of the file, please search the previous articles of the software development network or continue to browse the relevant articles below. I hope you can support the software development network in the future !



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