How to Handle IOError When Reading or Writing Files in Python

To handle IOError when reading or writing files in Python, use a try-except block. This helps catch exceptions caused by issues such as missing files, lack of permissions, or file system errors, allowing the program to handle the error gracefully instead of crashing.


Examples for Handling IOError with Files

1. Handling IOError When Reading a Non-Existent File

If we try to read a file that does not exist, Python raises a FileNotFoundError. We can handle this using a try-except block.

main.py

</>
Copy
try:
    # Attempting to open a non-existent file
    with open("non_existent_file.txt", "r") as file:
        content = file.read()
        print(content)
except IOError as e:
    print(f"Error: {e.strerror}. File not found!")

Explanation:

Here, we try to open a file named non_existent_file.txt in read mode using open(). Since the file does not exist, Python raises an IOError (which in modern Python is an alias for FileNotFoundError). The except block catches the error and prints a user-friendly message, preventing the program from crashing.

Output:

2. Handling IOError When Writing to a Read-Only File

Attempting to write to a read-only file raises a PermissionError, which can be handled using IOError in a try-except block.

main.py

</>
Copy
try:
    # Attempting to write to a read-only file
    with open("readonly.txt", "w") as file:
        file.write("This should cause an error.")
except IOError as e:
    print(f"Error: {e.strerror}. You don't have write permissions!")

Explanation:

Here, we attempt to open readonly.txt in write mode using open(). If the file is set to read-only mode, Python raises an IOError (specifically PermissionError). The except block catches this error and prints a helpful message to the user.

Output:

3. Handling IOError When Reading a File in Use

If a file is locked or in use by another process, an IOError can occur. This can be handled using try-except.

main.py

</>
Copy
try:
    # Trying to read a file that is in use
    with open("locked_file.txt", "r") as file:
        content = file.read()
        print(content)
except IOError as e:
    print(f"Error: {e.strerror}. File is currently in use!")

Explanation:

If another program (like a text editor) is using locked_file.txt, trying to open it for reading might raise an IOError. The except block catches this error and informs the user that the file is currently in use.

Output:

Error: Resource temporarily unavailable. File is currently in use!

4. Handling IOError Due to Insufficient Disk Space

If the disk runs out of space while writing to a file, Python raises an OSError which can be caught as an IOError.

main.py

</>
Copy
try:
    # Trying to write a large amount of data
    with open("large_file.txt", "w") as file:
        file.write("A" * 10**9)  # Writing 1GB of data
except IOError as e:
    print(f"Error: {e.strerror}. Insufficient disk space!")

Explanation:

We attempt to write 1GB of data to large_file.txt. If the disk is full, Python raises an OSError, which is caught as an IOError. The except block then prints an appropriate error message.

Output:

Error: No space left on device. Insufficient disk space!

Conclusion

To handle IOError effectively when working with files in Python, use try-except blocks to catch potential errors and prevent program crashes. Here are some key scenarios:

  1. File not found: Use except IOError to handle missing files.
  2. Read-only file: Catch permission errors when writing to files.
  3. File in use: Handle cases where a file is locked.
  4. Insufficient disk space: Catch errors caused by lack of storage.