Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does python determine whether a file or folder exists

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how python determines whether a file or folder exists. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

When Python manipulates files, we usually have to determine whether the specified file or directory exists, otherwise it is easy to generate exceptions.

1. Whether the file # exists import osos.path.exists (test_file.txt) # is the file import osos.path.isfile ("test-data") # is the file from pathlib import Pathmy_file = Path ("/ path/to/file") my_file.is_file () 2. Whether the folder # import osos.path.exists (test_dir) # is the folder from pathlib import Pathmy_file = Path ("/ path/to/file") my_file.is_dir () # whether there is from pathlib import Pathmy_file = Path ("/ path/to/file") my_file.exists () 3. Supplement

For example, we can use the os.path.exists () method of the os module to detect the existence of a file:

Import os.pathos.path.isfile (fname)

If you want to determine whether it is a file or a directory, you can use the object-oriented method provided by the pathlib module (Python 2.7is the pathlib2 module) starting with Python 3.4:

From pathlib import Pathmy_file = Path ("/ path/to/file") if my_file.is_file (): # the specified file exists

Check if it is a directory:

If my_file.is_dir (): # the specified directory exists

You can use the exists () method if you want to detect that the path is a file or directory:

If my_file.exists (): # the specified file or directory exists

In the try block, you can use the resolve () method to determine:

Try: my_abs_path = my_file.resolve () except FileNotFoundError: # there is no else: # Thank you for reading! This is the end of the article on "how to determine whether a file or folder exists in python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report