File Handling in Python
Reading and Writing Text Files in Python
Python provides simple methods to read and write text files. These operations are essential for saving data, logs, configurations, or exports.
Writing to a file
f = open("file.txt", "w")
f.write("Hello, John!")
f.close()
Reading from a file
f = open("file.txt", "r")
content = f.read()
print(content)
f.close()
File modes
"r" # read
"w" # write (overwrite)
"a" # append
"r+" # read and write
- Files must be closed manually with
close()to free resources. - Mode
"w"will delete existing content. - You can read the file line by line with
readline()orreadlines().
Opening files with with open() in Python
The with open() statement is the safest and recommended way to work with files in Python. It
automatically handles file closure, even if errors occur.
Writing with with open()
with open("file.txt", "w") as f:
f.write("Hello, John!")
Reading with with open()
with open("file.txt", "r") as f:
content = f.read()
print(content)
Reading line by line
with open("file.txt", "r") as f:
for line in f:
print(line.strip())
withcreates a context that automatically closes at the end.- It is ideal for avoiding errors related to open files.
- Works with all modes:
"r","w","a","r+".
Handling Exceptions with try - except - finally
In Python, errors can be gracefully handled using try, except, and
finally blocks. These allow controlling program behavior in case of exceptions.
Simple example
try:
f = open("file_not_existing.txt", "r")
except FileNotFoundError:
print("The file was not found.")
finally:
print("The operation has ended.")
Explanations
try: code that may raise an exception.except: code that runs if an exception occurs.finally: code that runs whether or not an exception occurred.
Multiple types of exceptions
try:
x = int(input("Enter a number: "))
result = 10 / x
except ValueError:
print("You did not enter a valid number.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
finally:
print("Calculation done.")
- You can have multiple
exceptblocks for different types of errors. finallyis optional but useful for cleanup (e.g., closing files).- It is good practice to handle exceptions to prevent program crashes.
Saving Data to Files
To save data to files, we use "w" (write) or "a" (append) mode. These create the
file if it does not exist.
Simple write
with open("date.txt", "w") as f:
f.write("Name: John\nAge: 25")
Appending content
with open("date.txt", "a") as f:
f.write("\nCity: Bristol")
"w"overwrites the entire file."a"appends to the end of the file.- You can save any type of text: results, settings, logs, etc.
Reading and Writing JSON and CSV
Python offers native support for working with .json and .csv files, commonly used in
web applications, databases, and data analysis.
JSON - JavaScript Object Notation
import json
# Save to JSON file
data = {"name": "John", "age": 25}
with open("date.json", "w") as f:
json.dump(data, f)
# Read from JSON file
with open("date.json", "r") as f:
loaded = json.load(f)
print(loaded)
CSV - Comma-Separated Values
import csv
# Write to CSV file
with open("date.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
writer.writerow(["John", 25])
# Read from CSV file
with open("date.csv", "r") as f:
reader = csv.reader(f)
for line in reader:
print(line)
json.dump()saves a dictionary to a file.json.load()loads the data back as a dictionary.csv.writer()writes rows in tabular format.csv.reader()reads each line as a list.
Practical Exercises
Practice working with files in Python through the following challenges. You can test the code directly in your editor.
1. Write a file with your data
with open("profil.txt", "w") as f:
f.write("Name: John\nAge: 25\nCity: London")
2. Read and display the file content
with open("profil.txt", "r") as f:
print(f.read())
3. Save a dictionary in JSON format
import json
data = {"name": "John", "email": "John@example.com"}
with open("profil.json", "w") as f:
json.dump(data, f)
4. Create a CSV file with multiple users
import csv
users = [
["Name", "Age", "City"],
["John", 25, "London"],
["Maria", 30, "Manchester"],
["Andrew", 22, "Bristol"]
]
with open("utilizatori.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(users)
5. Handle an exception when reading a non-existent file
try:
with open("inexistent.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("The file does not exist.")
- Create a program that reads a file line by line and counts how many lines it contains.
- Write a file that saves game scores and reads them later.
- Use
try-exceptto check if the file exists before reading.
