Opening files
To work with files in Python, use the built-in function open(). The basic syntax is:
file = open('filename.txt', 'mode')Main opening modes:
'r'— read. The file must exist'w'— write. Creates a new file or overwrites an existing one'a'— append. Appends data to the end of the file'r+'— read and write'b'— binary mode (for example,'rb'or'wb')
Reading files
Reading all content:
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)Line-by-line reading:
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip()) # strip() removes line breaksReading all lines in the list:
with open('example.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
print(lines)Writing to files
Text recording (file overwriting):
with open('output.txt', 'w', encoding='utf-8') as file:
file.write('Hello world!\n')
file.write('This is the second line.')Adding text to the end of the file:
with open('output.txt', 'a', encoding='utf-8') as file:
file.write('\nAdditional line')Writing a list of lines:
lines = ['First line\n', 'Second line\n', 'Third line\n']
with open('output.txt', 'w', encoding='utf-8') as file:
file.writelines(lines)Construction with
Using with is the best practice when working with files. It automatically closes the file after executing the code block, even if an error occurs.
Without with (not recommended):
file = open('example.txt', 'r')
content = file.read()
file.close() # Don't forget to close the file!With (recommended):
with open('example.txt', 'r') as file:
content = file.read()
# The file is automatically closed after exiting the blockWorking with file paths
To work with paths conveniently, use the pathlib module:
from pathlib import Path
# Creating a path
file_path = Path('folder') / 'subfolder' / 'file.txt'
# Checking the existence
if file_path.exists():
print('File exists')
# Reading file
content = file_path.read_text(encoding='utf-8')
# Write to file
file_path.write_text('New content', encoding='utf-8')
Error handling
When working with files, it is important to handle possible errors:
try:
with open('nonexistent.txt', 'r', encoding='utf-8') as file:
content = file.read()
except FileNotFoundError:
print('File not found')
except PermissionError:
print('No access rights to the file')
except Exception as e:
print(f'An error occurred: {e}')Working with CSV files
Python has a built-in module csv for working with CSV files:
import csv
# Reading CSV
with open('data.csv', 'r', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# CSV record
data = [
['Name', 'Age', 'City'],
['Alexey', '25', 'Moscow'],
['Maria', '30', 'St. Petersburg']
]
with open('output.csv', 'w', encoding='utf-8', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)Working with JSON files
To work with JSON, use the json module:
import json
# Reading JSON
with open('data.json', 'r', encoding='utf-8') as file:
data = json.load(file)
print(data)
# JSON record
data = {
'name': 'Ivan',
'age': 28,
'skills': ['Python', 'JavaScript']
}
with open('output.json', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)Practical examples
Counting the number of lines in a file:
with open('example.txt', 'r', encoding='utf-8') as file:
line_count = sum(1 for line in file)
print(f'Number of lines: {line_count}')Search for a word in a file:
search_word = 'Python'
with open('example.txt', 'r', encoding='utf-8') as file:
for line_number, line in enumerate(file, 1):
if search_word in line:
print(f'Found in line {line_number}: {line.strip()}')Copying file:
with open('source.txt', 'r', encoding='utf-8') as source:
with open('destination.txt', 'w', encoding='utf-8') as destination:
destination.write(source.read())Useful tips
Always specify the encoding. Use encoding='utf-8' to work correctly with Russian text.
Use with to automatically close files. This prevents resource leaks and data loss.
Handle exceptions. Files may not exist, be locked, or you may not have access rights.
Check the existence of files. Before reading, make sure that the file exists using Path.exists() or exception handling.
Be careful with large files. The read() method loads the entire file into memory. For large files, it is better to read line by line.
Conclusion
Working with files in Python is simple and intuitive. Basic principles: use the with construction, do not forget about error handling and choose the correct file opening mode. With this knowledge, you are ready to work effectively with files in your projects!
Code is a friendly community of developers where everyone can learn programming, share experiences, and get support from like-minded people. We have created a space where beginners feel comfortable asking any questions, and experienced programmers are happy to share their knowledge and help them grow.
Join Kodik — here the code is written easier, and the training takes place in an atmosphere of mutual assistance and inspiration!
