Check if a File Exists Before Reading or Writing in Python

To check if a file exists before reading or writing in Python, you can use the os.path.exists() function or the pathlib.Path.exists() method. These methods help prevent errors that occur when trying to read a non-existent file or overwrite an existing file unintentionally.


Examples

1. Using os.path.exists() to Check File Existence

The os.path.exists() function checks if a file or directory exists before performing operations on it.

main.py

</>
Copy
import os

file_path = "example.txt"

# Check if the file exists
if os.path.exists(file_path):
    print("The file exists.")
else:
    print("The file does not exist.")

Explanation:

  1. The variable file_path stores the name of the file.
  2. The function os.path.exists(file_path) checks if the file exists. We are using the returned value as a condition for if-else statement.
  3. If the file exists, the function returns True, it prints "The file exists.", otherwise, it prints "The file does not exist.".

Output:

2. Using pathlib.Path.exists() for File Existence Check

The pathlib module provides an object-oriented way to handle filesystem paths.

main.py

</>
Copy
from pathlib import Path

file_path = Path("example.txt")

# Check if the file exists
if file_path.exists():
    print("The file exists.")
else:
    print("The file does not exist.")

Explanation:

  1. Path("example.txt") creates a Path object.
  2. file_path.exists() checks if the file exists.
  3. Depending on the result, an appropriate message is printed.

Output:

3. Checking File Existence Before Reading

Before reading a file, it is good practice to check if it exists to avoid FileNotFoundError.

main.py

</>
Copy
import os

file_path = "example.txt"

# Check if the file exists before reading
if os.path.exists(file_path):
    with open(file_path, "r") as file:
        content = file.read()
    print("File Content:\n", content)
else:
    print("Error: The file does not exist.")

Explanation:

  1. The os.path.exists(file_path) checks if example.txt exists.
  2. If the file exists, it is opened using open() in read mode.
  3. The contents are read and printed.
  4. If the file does not exist, an error message is displayed.

Output:

4. Checking File Existence Before Writing

Before writing to a file, you may want to check if it already exists to avoid accidental overwriting.

main.py

</>
Copy
import os

file_path = "output.txt"

# Check if the file already exists
if os.path.exists(file_path):
    print("The file already exists. Choose a different filename.")
else:
    with open(file_path, "w") as file:
        file.write("Hello, Python!")
    print("File created successfully.")

Explanation:

  1. The os.path.exists(file_path) checks if output.txt exists.
  2. If the file exists, it warns the user.
  3. If the file does not exist, it creates and writes "Hello, Python!" to it.

Output:

If you try to run the program second time, after creating the file, you would get the following output.

Conclusion

In this tutorial, we have covered following methods to check if a file exists before reading or writing in Python:

  1. Use os.path.exists() for simple file existence checks.
  2. Use pathlib.Path.exists() for an object-oriented approach.
  3. Always check file existence before reading to avoid FileNotFoundError.
  4. Check before writing to prevent overwriting important data.