- Reading and Writing Text Files
- Working with Binary Files
- Using Context Managers (with statement)
- File Methods and Operations
- Handling File Exceptions
- Summary
- Tasks
In Python, you can read and write text files using the built-in open()
function. The open()
function takes two arguments: the file name and the mode in which the file should be opened.
You can read the contents of a text file using the read()
, readline()
, or readlines()
methods.
# Reading the entire file
with open("file.txt", "r") as f:
content = f.read()
print(content)
# Reading the file line by line
with open("file.txt", "r") as f:
for line in f:
print(line.strip())
Output:
1) The wind howls through the empty streets, carrying whispers of forgotten tales.
2) A flickering streetlight casts long shadows on the ground, adding to the mystery.
3) In the distance, a train’s whistle echoes, announcing its arrival in the quiet town.
4) The smell of fresh bread wafts through the air from a bakery nearby.
5) Leaves rustle underfoot as people walk, their footsteps blending with the natural sounds.
You can write to a text file using the write()
method. If the file does not exist, it will be created.
# Writing to a file
with open("langs.txt", "w") as f:
f.write("Python\nKotlin\nC++\nTypeScript\nC#")
# Appending to a file
with open("langs.txt", "a") as f:
f.write("\nJavaScript")
Output in langs.txt
:
Python
Kotlin
C++
TypeScript
C#
JavaScript
Binary files store data in binary format. You can read and write binary files using the rb
and wb
modes.
with open("image.jpg", "rb") as f:
content = f.read()
print(content[:20]) # Print the first 20 bytes
with open("copy.jpg", "wb") as f:
f.write(content)
The with
statement is used to wrap the execution of a block of code. It ensures that resources are properly managed, such as closing a file after it has been opened.
with open("file.txt", "r") as f:
content = f.read()
print(content)
Explanation: The with
statement ensures that the file is properly closed after it has been read.
Python provides several methods and operations for working with files.
import os
if os.path.exists("file.txt"):
print("The file exists.")
else:
print("The file does not exist.")
if os.path.exists("test.txt"):
os.remove("test.txt")
else:
print("There is no such file to delete.")
os.rename("old_name.txt", "new_name.txt")
file_info = os.stat("file.txt")
print(f"File size: {file_info.st_size} bytes")
print(f"Last modified: {file_info.st_mtime}")
When working with files, you may encounter exceptions. It is important to handle these exceptions to prevent your program from crashing.
try:
with open("non_existent_file.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("The file does not exist.")
except IOError:
print("An I/O error occurred.")
Explanation: The try-except
block is used to handle exceptions that may occur when working with files.
In this chapter, we covered file handling in Python, including reading and writing text files, working with binary files, using context managers, file methods and operations, and handling file exceptions.
- Write a program that reads a text file and prints its contents to the screen.
- Write a program that writes a list of strings to a text file.
- Write a program that reads a binary file and prints the first 20 bytes.
- Write a program that checks if a file exists and deletes it if it does.
- Write a program that handles exceptions when trying to read a non-existent file.