Reading Files
Python reads and writes files through file objects. In text mode, the file object decodes stored bytes into strings using a chosen encoding. In binary mode, it exposes the bytes unchanged.
For AI agents: use /llms.txt for the Nakafa content index.
Python reads and writes files through file objects. In text mode, the file object decodes stored bytes into strings using a chosen encoding. In binary mode, it exposes the bytes unchanged.
The simplest way to read a file is to take all its contents at once into memory.
# Read the entire UTF-8 text file at once
with open('file.txt', 'r', encoding='utf-8') as f:
txt = f.read()
print(txt)
# Output: [complete file content will be displayed]open() creates the file object, read() consumes its text, and the with block closes the file automatically when the block ends, including when an exception interrupts the operation.
For large files, reading line by line is more efficient because it doesn't load the entire file into memory at once.
# Read a UTF-8 text file line by line
with open('file.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line, end='')
# Note: each line retains its newline character
# Parameter end='' prevents adding additional newlineEach line retains its ending newline when one exists. The final line may have no newline. Setting end='' prevents print() from adding a second one.
Writing files allows programs to save data or calculation results into files for later use.
# Write strings to a UTF-8 text file
with open('file.txt', 'w', encoding='utf-8') as f:
for i in range(1, 11):
f.write(f'Line {i}\n')
# File will contain:
# Line 1
# Line 2
# Line 3
# ... (up to Line 10)You can redirect the output of the print() function directly to a file using the file parameter.
# Redirect print output to a UTF-8 text file
with open('file.txt', 'w', encoding='utf-8') as f:
for i in range(1, 21):
print("Line", i, file=f)
# File will contain redirected print output
# Line 1
# Line 2
# ... (up to Line 20)The file argument reuses print() formatting while directing the resulting text to the chosen file object.
Python provides various modes for opening files according to the needs of the operations to be performed.
# Read an existing text file
with open('data.txt', 'r', encoding='utf-8') as f:
first_line = f.readline()
# Create a file or truncate its previous content
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('new content')
# Create a file or append after its existing content
with open('log.txt', 'a', encoding='utf-8') as f:
f.write('next event\n')
# Read and write an existing file without truncating it on open
with open('data.txt', 'r+', encoding='utf-8') as f:
original = f.read()The mode controls whether a file must already exist, whether opening it truncates existing content, and which operations are allowed. r and r+ require an existing file. w creates or truncates, while a creates or appends. Adding b selects binary mode, where encoding is not used.
Python provides several methods to read files in different ways according to needs.
# Explore several text-reading methods
with open('file.txt', 'r', encoding='utf-8') as f:
# Read at most 10 characters
s = f.read(10)
print("10 characters:", s)
# Return to the beginning and read the rest of the file
f.seek(0)
s = f.read()
print("Entire file:", s)
# Return again and read one line, including its newline if present
f.seek(0)
s = f.readline()
print("One line:", repr(s))A newly opened file starts at its initial stream position. Reading advances that position. In text mode, tell() can return an opaque position cookie rather than a simple character index, so store and reuse positions instead of calculating byte offsets yourself.
# File-position demonstration
with open('sample.txt', 'r', encoding='utf-8') as f:
first_read = f.read(5) # Read at most 5 characters
saved_position = f.tell()
print("First read:", first_read)
second_read = f.read(3) # Continue from the current position
print("Second read:", second_read)
f.seek(saved_position) # Return to the saved text-stream position
repeated = f.read(3)
print("Repeated read:", repeated)In text mode, read() and readline() return strings and return '' when no more text is available. In binary mode they return bytes and use b'' at end of file. Iteration stops automatically at the end.
Python provides the with statement for safer and automatic file handling.
# Using with statement for safe file handling
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# File automatically closed after exiting with block
# Writing with with statement
with open('output.txt', 'w', encoding='utf-8') as f:
f.write("Hello World!")
f.write("\nSecond line")
# File automatically closed and saved
# Reading and writing simultaneously
with open('input.txt', 'r', encoding='utf-8') as input_file, open('output.txt', 'w', encoding='utf-8') as output_file:
data = input_file.read()
output_file.write(data.upper())
# Both files automatically closedThe with statement ensures files are always closed properly, even if an error occurs in the program. This prevents problems like files staying open and consuming system resources.