Skip to main content

Python File Handling

Python File Handling

File handling in Python allows you to read from and write to files, enabling data persistence and interaction with external resources. This tutorial explores how to open, read, write, and manage files effectively, using open() and context managers.


01. What Is File Handling?

File handling involves operations like reading data from a file or writing data to it. Python uses the open() function to access files, and the with statement ensures proper resource management.

Example: Reading a File

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

Output: (Assuming example.txt contains "Hello, Python!")

Hello, Python!

Explanation:

  • open("example.txt", "r") - Opens the file in read mode.
  • with - Ensures the file is properly closed after use.

02. Common File Operations

Python supports various file operations, including reading, writing, and appending, with different modes to control access.

Mode Description Example
"r" Read mode (default) open("file.txt", "r")
"w" Write mode (overwrites file) open("file.txt", "w")
"a" Append mode (adds to end) open("file.txt", "a")
"r+" Read and write mode open("file.txt", "r+")


2.1 Reading Files

Example: Reading Line by Line

with open("example.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())  # Remove trailing newlines

Output: (Assuming example.txt contains two lines)

Line 1
Line 2

2.2 Writing Files

Example: Writing to a File

with open("output.txt", "w") as file:
    file.write("Welcome to Python!\n")
    file.write("File handling is easy.")

Output: (Creates output.txt with the content)

Welcome to Python!
File handling is easy.

2.3 Invalid File Operation

Example: File Not Found Error

with open("missing.txt", "r") as file:
    content = file.read()

Output:

FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'

Explanation:

  • open("missing.txt", "r") - Attempting to read a non-existent file causes a FileNotFoundError.

03. Handling File Exceptions

Exception handling is crucial for robust file operations, allowing you to manage errors like missing files or permission issues.

Example: Exception Handling

try:
    with open("data.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("Error: File not found!")
except PermissionError:
    print("Error: Permission denied!")
else:
    print("File read successfully!")

Output: (If data.txt is missing)

Error: File not found!

04. Effective Usage

4.1 Recommended Practices

  • Always use the with statement to ensure files are closed properly.

Example: Using with Statement

# Good: Automatic file closing
with open("log.txt", "w") as file:
    file.write("Log entry")

# Avoid: Manual closing
file = open("log.txt", "w")
file.write("Log entry")
file.close()  # Risk of forgetting
  • Handle specific file-related exceptions (e.g., FileNotFoundError).
  • Use appropriate file modes for the intended operation.

4.2 Practices to Avoid

  • Avoid opening files without exception handling.

Example: Unhandled Error

content = open("missing.txt", "r").read()  # Crashes if file is missing

Output:

FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
  • Don’t forget to close files when not using with.

05. Common Use Cases

5.1 Logging Data

Files are often used to log program activity or results.

Example: Writing a Log

try:
    with open("log.txt", "a") as file:
        file.write("User logged in at 2023-10-01\n")
except PermissionError:
    print("Cannot write to log file!")

Output: (Appends to log.txt)

User logged in at 2023-10-01

5.2 Reading Configuration Files

Files can store configuration settings for programs.

Example: Reading Config

try:
    with open("config.txt", "r") as file:
        settings = file.readlines()
        for setting in settings:
            print(setting.strip())
except FileNotFoundError:
    print("Config file not found!")

Output: (Assuming config.txt contains "theme=dark\nfont=Arial")

theme=dark
font=Arial

Conclusion

Python file handling enables seamless interaction with external files for reading and writing data. By mastering open(), with, and exception handling, you can manage files robustly. Key takeaways:

  • Use with for safe file operations.
  • Handle exceptions like FileNotFoundError to prevent crashes.
  • Choose correct file modes ("r", "w", "a") for tasks.
  • Leverage files for logging, configuration, or data storage.

With these skills, you’re ready to handle file operations confidently in your Python programs!

Comments