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.
Prepare four UTF-8 text files in your practice directory: file.txt, data.txt, sample.txt, and input.txt, each containing Halo Python without a final newline. Run the reading examples before the writing examples, since w replaces file contents. In the position example, the first read yields Halo , the second Pyt, and the repeated read also Pyt.
Reading Entire File Content
The read() method loads all remaining file content into memory at once:
# 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:
# Halo Pythonopen() 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.
Reading File Line by Line
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 to Files
Writing to a file keeps data or calculation results available after the program stops running. Python opens the file in a mode that decides whether existing content is replaced or extended, then writes through the returned file object.
Writing Strings to Files
This example uses w to replace the entire file content. Ten calls to write() occur inside one with block before the file closes.
# 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)Redirecting Print Output to File
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.
File Opening Modes
Python provides various modes for opening files according to the needs of the operations to be performed.
File Opening Syntax
# 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.
File Reading Methods
Python offers more than one way to read a file, and the choice depends on how much of the content you need at once and whether the read position matters afterwards. read() takes the whole remainder or at most a requested number of characters. readline() takes one line, while readlines() without arguments loads all remaining lines into a list.
Read Method with Parameters
read() accepts a size argument, so you can take a fixed number of characters at a time. The example compares reading at most ten characters, the entire content, and one line.
# 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))File Position and Reading
A file opened in r mode starts at its initial stream position. Reading advances that position. In text mode, tell() may return a special position marker. Save that marker and pass it back to Python when you need the same position.
# 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.
Safe File Handling
The with statement closes a file automatically when its block ends, including when an operation inside the block raises an exception.
# 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 a 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.