Basics of working with files in Python
Working with files in Python is an important skill for every developer. The correct opening and closing of files ensures the correct operation of the program and the efficient use of system resources.
The open() function for working with files
The open() function is the main tool for working with files in Python. It accepts two required parameters: the file path and the access mode.
file = open("example.txt", "r")
File opening modes
Choosing the correct file opening mode is crucial for the correct operation of the program:
mode
| Description | |
|---|---|
'r' |
Opening a file for reading (default mode) |
'w' |
Writing to a file (creates a new file or overwrites an existing one) |
'a' |
Adding data to the end of the file |
'x' |
Creating a new file (fails if the file exists) |
'rb' |
Reading a file in binary mode |
'wb' |
Writing to a file in binary mode |
'ab' |
Adding to a file in binary mode |
'r+' |
Reading and writing to an existing file |
'w+' |
Reading and writing (creates a new file or overwrites) |
'a+' |
Reading and appending to the end of the file |
Correct closing of files
Closing a file using the close() method frees up system resources and ensures that all changes are saved.:
file = open("example.txt ", "r")
# working with the file
file.close()
Context manager with best practice
Using the context manager with ensures that the file is automatically closed even when exceptions occur.:
with open("example.txt", "r") as file:
data = file.read()
print(data)
# The file closes automatically after exiting the block
Checking the existence of a file
Before working with a file, it is recommended to check its existence using the os module:
import os
if os.path.exists("example.txt"):
with open("example.txt", "r") as file:
content = file.read()
print("File contents:", content)
else:
print("File not found")
An alternative method using pathlib:
from pathlib import Path
file_path = Path("example.txt")
if file_path.exists():
with open(file_path, "r") as file:
content = file.read()
Working with files in binary mode
Binary mode is necessary for working with images, archives, videos, and other non-text files.:
# Reading a binary file
with open("image.jpg", "rb") as file:
data = file.read()
print(f"File size: {len(data)} bytes")
# Copying a binary file
with open("source.jpg", "rb") as source:
with open("copy.jpg", "wb") as destination:
destination.write(source.read())
Exception handling when working with files
To work reliably with files, it is important to handle possible exceptions.:
try:
with open("example.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Insufficient permissions to access the file")
except Exception as e:
print(f"Error occurred: {e}")
File encoding
When working with text files, it is important to specify the correct encoding:
# Explicit UTF-8 encoding
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
# Windows may require cp1251
with open("example.txt", "r", encoding="cp1251") as file:
content = file.read()
Practical examples
Reading the file line by line:
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
Writing data to a file:
data = ["Line 1", "Line 2", "Line 3"]
with open("output.txt ", "w") as file:
for item in data:
file.write(item + "\n")
Adding data to an existing file:
with open("log.txt", "a") as file:
file.write("New log entry\n")
Conclusion
Working with files correctly in Python requires understanding access modes, using context managers, and exception handling. Following these principles ensures the reliability and efficiency of your programs when working with the file system.