import os.path if os.path.exists('myfile.txt'): print('The file exists.') else: print('The file does not exist.')
To check whether a file exists in Python without raising any exceptions, you can use the os.path.exists() method. This method takes a single argument, which is the name of the file, and returns True if the file exists and False if it does not.
In the above example, the code checks if the file myfile.txt exists in the current directory. If it exists, it prints "The file exists.". If it does not exist, it prints "The file does not exist." Another way to check if a file exists in Python is to use the try and except keywords to catch any exceptions that may be raised.
try: with open('myfile.txt') as f: pass except FileNotFoundError: print('The file does not exist.') else: print('The file exists.')
This code attempts to open the file myfile.txt using a with statement. If the file does not exist, a FileNotFoundError exception will be raised, and the code in the except block will be executed. If the file does exist, the code in the else block will be executed. This approach can be useful if you want to perform some additional actions when the file exists, such as reading its contents or appending data to it.
Overall, the os.path.exists() method is the easiest and most straightforward way to check if a file exists in Python. It is also the most efficient, as it does not involve trying to open the file, which can be slow and resource-intensive.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.