A file is where data is stored. Python allows you to:
- Read data from files.
- Write data to files.
- Manage files (e.g., delete or rename them).
Files can store text (.txt
) or binary data (images, videos, etc.).
2. Opening a File
To work with files, you need to open them first using the open()
function.
file = open("example.txt", "r") # Opens the file 'example.txt' in read mode
Common Modes:
"r"
: Read (default mode)."w"
: Write (creates a new file or overwrites an existing one)."a"
: Append (adds data to an existing file)."rb"
/"wb"
: Read/Write binary files.
3. Reading Files
Example 1: Read the Entire File
with open("example.txt", "r") as file:
content = file.read()
print(content)
Explanation:
with open(...) as file
: Automatically closes the file after the block is done.file.read()
: Reads the whole file content.
Sample Output:
Hello, this is an example text file.
It has multiple lines of text.
Example 2: Read Line by Line
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # `.strip()` removes extra spaces or newline characters
Sample Output:
Hello, this is an example text file.
It has multiple lines of text.
4. Writing to Files
Use "w"
mode to write new data. Be careful—it will overwrite the file!
with open("output.txt", "w") as file:
file.write("Python makes file handling easy!\n")
file.write("This is another line.\n")
Sample Output in output.txt
:
Python makes file handling easy!
This is another line.
5. Appending to Files
Use "a"
mode to add content without overwriting.
with open("output.txt", "a") as file:
file.write("This is an appended line.\n")
Updated output.txt
:
Python makes file handling easy!
This is another line.
This is an appended line.
6. Checking if a File Exists
Sometimes, you want to avoid errors if a file doesn’t exist. Use the os
module.
import os
if os.path.exists("example.txt"):
print("The file exists!")
else:
print("The file does not exist.")
Sample Output:
The file exists!
7. Deleting a File
Use os.remove()
to delete files.
import os
if os.path.exists("output.txt"):
os.remove("output.txt")
print("File deleted!")
else:
print("File not found.")
Sample Output:
File deleted!
8. Writing a List of Data to a File
You can write multiple lines using a list.
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("list_output.txt", "w") as file:
file.writelines(lines)
Output in list_output.txt
:
First line
Second line
Third line
9. Reading Files into a List
You can read all lines into a list for easy processing.
with open("list_output.txt", "r") as file:
lines = file.readlines()
print(lines)
Sample Output:
['First line\n', 'Second line\n', 'Third line\n']
10. Working with CSV Files
Python has a built-in csv
module to handle comma-separated values.
Writing a CSV File:
import csv
data = [["Name", "Age"], ["Alice", 25], ["Bob", 30]]
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
Sample data.csv
:
Name,Age
Alice,25
Bob,30
Reading a CSV File:
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Sample Output:
['Name', 'Age']
['Alice', '25']
['Bob', '30']
11. File Paths
You can work with files in different folders using full paths.
Example:
with open("C:/Users/YourName/Documents/example.txt", "r") as file:
print(file.read())
12. Error Handling with Files
Avoid crashes using try-except
blocks.
try:
with open("nonexistent.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("The file does not exist.")
Sample Output:
The file does not exist.
13. File Management Utilities
- Rename a File:
import os os.rename("oldname.txt", "newname.txt")
- Create a File:
with open("newfile.txt", "w") as file: pass # Creates an empty file
14. Binary Files
Binary files store data like images or videos. Use "rb"
and "wb"
modes.
Reading Binary Files:
with open("image.jpg", "rb") as file:
data = file.read()
print(f"File size: {len(data)} bytes")
Writing Binary Files:
with open("copy.jpg", "wb") as file:
file.write(data)