How do you read and write files in Python?

Reading and writing files in Python is straightforward using built-in file-handling functions. Python provides the open() function for accessing files and several modes for reading, writing, or appending content.


1. Basic File Operations

Opening a File

The open() function is used to open a file. It takes two arguments:

  • file (required): The file name or path.
  • mode (optional): The mode for opening the file (default is 'r' for reading).

Common modes:

  • 'r': Read (default mode). The file must exist.
  • 'w': Write. Creates a new file or overwrites an existing file.
  • 'a': Append. Adds data to the end of the file if it exists.
  • 'r+': Read and write. The file must exist.

2. Reading Files

Reading the Entire File

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

Reading Line by Line

with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())  # `.strip()` removes newline characters

Reading with readlines()

Returns a list of all lines in the file.

with open('example.txt', 'r') as file:
    lines = file.readlines()
    print(lines)

3. Writing Files

Writing Data with 'w' Mode

This mode overwrites the file if it exists.

with open('example.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.")

Appending Data with 'a' Mode

This mode adds content to the file without overwriting.

with open('example.txt', 'a') as file:
    file.write("\nThis line is appended.")

4. Working with Binary Files

Reading a Binary File

with open('example.png', 'rb') as file:
    content = file.read()
    print(content[:20])  # Print the first 20 bytes

Writing to a Binary File

with open('copy.png', 'wb') as file:
    file.write(content)

5. Using seek() and tell()

  • file.seek(offset, whence): Moves the file pointer.
    • offset: Number of bytes to move.
    • whence: Starting point (0 for beginning, 1 for current position, 2 for end).

Example:

with open('example.txt', 'r') as file:
    file.seek(10)  # Move pointer to the 10th byte
    content = file.read()
    print(content)
  • file.tell(): Returns the current file pointer position.
with open('example.txt', 'r') as file:
    print(file.tell())

6. Handling File Exceptions

Always handle file operations with try-except blocks to avoid errors when a file is missing or inaccessible.

Example:

try:
    with open('nonexistent.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")
except IOError:
    print("An error occurred while accessing the file.")

7. Working with Paths

Use the os and pathlib modules for advanced file handling and compatibility across operating systems.

Example with pathlib:

from pathlib import Path

# Check if a file exists
file_path = Path("example.txt")
if file_path.exists():
    print(f"{file_path} exists.")
else:
    print(f"{file_path} does not exist.")

8. Best Practices

  • Use the with statement: It ensures that files are properly closed, even if an error occurs.
  • Handle exceptions: Always account for potential errors like missing files.
  • Avoid overwriting files unintentionally: Be cautious when using 'w' mode.
  • Use pathlib for better file path handling.

By following these practices, you can handle files effectively and avoid common pitfalls.