Read a File Character by Character in Python

To read a file character by character in Python, we can use the built-in open() function to open the file and the read(1) method to fetch one character at a time. This method is useful when processing large files efficiently without loading the entire content into memory.


Examples

1. Reading a File Character by Character Using read(1)

In this example, we use read(1) inside a loop to read one character at a time until we reach the end of the file.

main.py

</>
Copy
# Open the file in read mode
with open("sample.txt", "r") as file:
    while True:
        char = file.read(1)  # Read one character at a time
        if not char:  # Break the loop if end of file is reached
            break
        print(char)

Explanation:

  • open("sample.txt", "r"): Opens the file in read mode.
  • file.read(1): Reads a single character from the file.
  • if not char: Checks if the end of the file (EOF) is reached. Refer: if statement, not operator.
  • print(char): Prints the character with a trialing new line.

Output:

If sample.txt contains Hello World, the script prints each character sequentially.

2. Reading a File Character by Character Using a for Loop

Instead of read(1), we can iterate directly over the file object to read characters one by one.

main.py

</>
Copy
# Open the file in read mode
with open("sample.txt", "r") as file:
    for line in file:  # Iterate over each line
        for char in line:  # Iterate over each character in the line
            print(char)

Explanation:

  • for line in file: Reads the file line by line.
  • for char in line: Iterates over each character in the line.
  • print(char): Prints the character with a trialing new line.

Output:

The behavior is the same as the previous method, but it is more Pythonic.

3. Reading a File Character by Character Using iter() and functools.partial()

For large files, we can use iter() with functools.partial() for efficient character-by-character reading.

main.py

</>
Copy
from functools import partial

# Open the file in read mode
with open("sample.txt", "r") as file:
    for char in iter(partial(file.read, 1), ''):  # Read one character until EOF
        print(char)

Explanation:

  • partial(file.read, 1): Calls file.read(1) repeatedly.
  • iter(..., ''): Iterates until an empty string (EOF) is encountered.

Output:

This method efficiently handles large files.

Conclusion

In this tutorial, we covered different ways to read a file character by character in Python with examples:

  1. Using read(1): Reads one character at a time in a loop.
  2. Using a for loop: Iterates over characters in a line.
  3. Using iter() and functools.partial(): Efficient for large files.