Python File Handling


File Handling in Python

File handling in Python refers to the process of creating, reading, writing, and manipulating files on the filesystem. Python provides built-in functions and methods to work with files efficiently, making it easy to handle text and binary data.

Opening a File

To work with a file in Python, you first need to open it using the open() function. The syntax is:

file_object = open(file_name, mode)
  • file_name: The name of the file you want to open (can include the path).
  • mode: A string indicating the mode in which the file is opened. Common modes include:
    • 'r': Read (default mode). Opens the file for reading.
    • 'w': Write. Opens the file for writing (creates a new file or truncates an existing one).
    • 'a': Append. Opens the file for writing (creates a new file or appends to an existing one).
    • 'b': Binary mode. Used for binary files (e.g., images).
    • 't': Text mode (default mode). Used for text files.

Closing a File

Always close the file after you're done to free up system resources using the close() method:

file_object.close()

File Handling Operations

1. Writing to a File

You can write to a file using the write() or writelines() methods.

# Writing to a file with open('example.txt', 'w') as file: file.write('Hello, World!\n') file.writelines(['Line 1\n', 'Line 2\n', 'Line 3\n'])

Using the with statement automatically closes the file after the block is executed, which is a best practice.

2. Reading from a File

To read from a file, use the read(), readline(), or readlines() methods.

  • read(size): Reads the entire file or up to size bytes.
  • readline(): Reads a single line from the file.
  • readlines(): Reads all lines and returns a list of strings.
# Reading from a file with open('example.txt', 'r') as file: content = file.read() # Read the entire file print(content) with open('example.txt', 'r') as file: line = file.readline() # Read the first line print(line) with open('example.txt', 'r') as file: lines = file.readlines() # Read all lines for line in lines: print(line.strip()) # Print each line without extra spaces

3. Appending to a File

To add new content to an existing file without overwriting it, open the file in append mode ('a').

with open('example.txt', 'a') as file: file.write('Line 4\n')

4. Working with Binary Files

When dealing with binary files (like images), use binary mode ('rb' for reading and 'wb' for writing).

# Writing a binary file with open('image.png', 'wb') as file: file.write(binary_data) # binary_data should be in bytes # Reading a binary file with open('image.png', 'rb') as file: binary_data = file.read()

File Handling Exceptions

It's important to handle exceptions that may occur during file operations, such as file not found or permission errors. You can use try-except blocks for this purpose.

try: with open('nonexistent.txt', 'r') as file: content = file.read() except FileNotFoundError: print("The file does not exist.") except IOError: print("An error occurred while handling the file.")

Summary

  • Opening a File: Use the open() function with the appropriate mode.
  • Writing to a File: Use write() or writelines() methods to write data.
  • Reading from a File: Use read(), readline(), or readlines() methods to read data.
  • Appending to a File: Open the file in append mode ('a') to add new data.
  • Binary Files: Use binary modes for reading and writing binary data.
  • Exception Handling: Use try-except blocks to handle file-related errors.

File handling is a fundamental aspect of programming, allowing you to persist data and work with external resources in your Python applications.