Get the App
SLTechnology News&Howtos  ›  Development  › 

How does python determine whether a file or folder exists

Shulou Source: shulou.com Published: 2022-06-01 05:01:04 10月05日 Update

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!

Tags: Files directories folders methods modules detection content more articles good practical objects articles look knowledge statements paths or reference help Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Technology Microsoft Redmi MariaDB