Basic file reading methods in Python
Complete reading of the file using the read() method
To read the entire contents of the file, the read() method is used, which returns data as a string. This method is optimal for small files that fit into RAM.
with open("example.txt", "r", encoding="utf-8") as file:
data = file.read()
print(data)
Important: Always specify the encoding encoding="utf-8" to work correctly with Russian characters.
Line-by-line reading of the file
The readline() method
Reads a file one line per call, which saves memory when working with large files.:
with open("example.txt", "r", encoding="utf-8") as file:
line = file.readline()
while line:
print(line.strip()) # strip() removes newline characters
line = file.readline()
The readlines() method
Reads all the lines of the file and returns them as a list:
with open("example.txt", "r", encoding="utf-8") as file:
lines = file.readlines()
for line in lines:
print(line.strip())
Iterating through the file (recommended method)
The most effective way to read line by line:
with open("example.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
Writing data to Python files
Complete overwriting of the file
'w' mode completely overwrites the contents of the file:
with open("example.txt", "w", encoding="utf-8") as file:
file.write("Hello, world!\n")
file.write("This is a test file.")
Adding data to the end of the file
'a' mode (append) adds new data to the end of the file, preserving the existing content.:
with open("example.txt", "a", encoding="utf-8") as file:
file.write("\This line will be added to the end of the file.")
Writing a list of strings
To write multiple lines, use the writelines() method:
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt ", "w", encoding="utf-8") as file:
file.writelines(lines)
Working with binary files
Reading binary files
with open("image.jpg", "rb") as file:
binary_data = file.read()
print(f"File size: {len(binary_data)} bytes")
Binary data recording
with open("image.jpg", "wb") as file:
file.write(binary_data)
Copying binary files
with open("source.jpg", "rb") as source:
with open("copy.jpg", "wb") as destination:
destination.write(source.read())
Exception handling when working with files
Always use exception handling to work reliably with files.:
try:
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found")
except PermissionError:
print("No file access rights")
except as e:
print(f"Error occurred: {e}")
Checking the existence of a file
Before working with the file, check its existence.:
import os
if os.path.exists("example.txt"):
with open("example.txt", "r", encoding="utf-8") as file:
print(file.read())
else:
print("The file does not exist")
Working with file paths
Use the pathlib module to work with paths conveniently:
from pathlib import Path
file_path = Path("data") / "example.txt"
if file_path.exists():
with open(file_path, "r", encoding="utf-8") as file:
content = file.read()
Practical examples
Counting lines in a file
def count_lines(filename):
try:
with open(filename, "r", encoding="utf-8") as file:
return sum(1 for line in file)
except FileNotFoundError:
return 0
print(f"Number of lines: {count_lines('example.txt ')}")
Text search in a
filedef search_in_file(filename, search_text):
try:
with open(filename, "r", encoding="utf-8") as file:
for line_num, line in enumerate(file, 1):
if search_text in line:
print(f"Line {line_num}: {line.strip()}")
except FileNotFoundError:
print("File not found")
Recommendations for working with files
- Always use the context manager
withto automatically close files - Specify the encoding
encoding="utf-8"when working with text files - Handle exceptions to improve code reliability
- For large files, use line-by-line reading to save memory
- Check the existence of files before attempting to open them