Working with files in Python? Ever needed to know if a file *actually* exists before trying to open or manipulate it? You're not alone! Fortunately, Python offers a straightforward way to check.
The most common method utilizes the `os.path.exists()` function. Simply import the `os.path` module and pass the file path as an argument. This function returns `True` if the file (or directory) exists at the specified path, and `False` otherwise. It's a quick and easy way to prevent errors like `FileNotFoundError`.
```python
import os.path
file_path = "my_file.txt"
if os.path.exists(file_path):
print(f"The file '{file_path}' exists!")
# Perform operations on the file
else:
print(f"The file '{file_path}' does not exist.")
```
Another option is using `pathlib`. The `pathlib` module provides an object-oriented way to interact with files and directories. You can create a `Path` object and then call its `exists()` method, which also returns `True` or `False`. Choose the method that best suits your coding style and project requirements. Both are equally effective for confirming file existence!