Python Course
File Handling in Python
In this lesson you will learn how to read from and write to files using Python. Almost every real program deals with files — saving user data, reading configuration settings, writing logs, or processing reports. By the end of this lesson you will be able to handle text files and CSV files with confidence.
1. What is File Handling?
File handling means opening a file on your computer, doing something with it (reading, writing, or adding to it), and then closing it. Python makes this very straightforward with the built-in open() function.
Why does file handling exist? Data stored in variables disappears the moment your program stops. Files let you persist data — save it so it is still there the next time the program runs. This is the foundation of every application that stores information.
Where is file handling used?
- Saving user accounts, orders, or settings to a file
- Reading a configuration file when an app starts
- Writing log files to track what happened in a program
- Processing sales reports or data exported as CSV files
- Reading and writing text content for web applications
2. File Modes
When you open a file, you tell Python what you want to do with it using a mode. The mode is the second argument to open(). Using the wrong mode is one of the most common beginner mistakes — knowing them upfront saves a lot of confusion.
| Mode | Meaning | What Happens |
|---|---|---|
| "r" | Read | Opens file to read. Error if file does not exist. |
| "w" | Write | Creates file. Overwrites if it already exists. |
| "a" | Append | Adds to end of file. Creates file if it does not exist. |
| "x" | Create | Creates new file. Error if file already exists. |
| "r+" | Read + Write | Opens for both reading and writing. |
3. Writing to a File
Use mode "w" to create a new file and write content into it. The safest way to work with files in Python is using a with statement — it automatically closes the file when the block finishes, even if an error occurs. You never need to call file.close() manually.
# Write to a file using "with" — it closes automatically when done
with open("notes.txt", "w") as file:
file.write("Python File Handling\n") # \n = new line
file.write("Lesson 19\n")
file.write("Dataplexa.com\n")
print("File written successfully.")
What just happened?
open("notes.txt", "w")creates a file callednotes.txtin the current folder. If the file already exists, its contents are erased and replaced.file.write()writes a string to the file. It does not add a new line automatically — you must add\nat the end of each line yourself.- The
withblock closes the file automatically when it ends — this is the correct and safe way to handle files in Python.
4. Reading a File
Use mode "r" to open an existing file and read its contents. Python gives you three ways to read — the whole file at once, one line at a time, or all lines into a list. Choose based on what you need.
# Method 1: read() — reads the entire file as one big string
with open("notes.txt", "r") as file:
content = file.read()
print("--- read() ---")
print(content)
# Method 2: readline() — reads one line at a time
with open("notes.txt", "r") as file:
print("--- readline() ---")
print(file.readline()) # reads first line
print(file.readline()) # reads second line
# Method 3: readlines() — reads all lines into a list
with open("notes.txt", "r") as file:
lines = file.readlines()
print("--- readlines() ---")
print(lines)
Python File Handling
Lesson 19
Dataplexa.com
--- readline() ---
Python File Handling
Lesson 19
--- readlines() ---
['Python File Handling\n', 'Lesson 19\n', 'Dataplexa.com\n']
What just happened?
read()returns the entire file content as one string — good when you want to process the whole file at once.readline()reads one line per call and moves a cursor forward — each call picks up where the last one left off.readlines()returns a list where each element is one line, including the\nat the end. Use.strip()to remove those if needed.
5. Looping Through a File Line by Line
The most memory-efficient way to read a file is to loop through it directly. Python reads one line at a time instead of loading the whole file into memory — this is essential when working with large files.
# Loop through each line directly — efficient for large files
with open("notes.txt", "r") as file:
for line in file:
# strip() removes the \n at the end of each line
print(line.strip())
Lesson 19
Dataplexa.com
What just happened?
- Looping directly over a file object (
for line in file) reads one line per iteration — Python handles the cursor automatically. line.strip()removes the\nnewline character at the end of each line so the output looks clean.- This approach works perfectly even on files with millions of lines because it never loads the entire file into memory at once.
6. Appending to a File
Mode "a" opens a file and adds new content to the end without deleting anything already there. This is used for log files, audit trails, and anywhere you want to keep adding records over time.
# First, write the initial content
with open("log.txt", "w") as file:
file.write("Log started\n")
# Append new entries without erasing the original
with open("log.txt", "a") as file:
file.write("User logged in\n")
file.write("File uploaded\n")
# Append again — keeps adding to the end
with open("log.txt", "a") as file:
file.write("User logged out\n")
# Read the full log to verify
with open("log.txt", "r") as file:
print(file.read())
User logged in
File uploaded
User logged out
What just happened?
- The first
"w"block created the file and wrote the first line. - Each
"a"block added new lines to the end without touching the existing content — the log grew with each block. - This is exactly how server log files, error trackers, and activity feeds work in real applications.
7. Checking if a File Exists Before Opening
Trying to open a file that does not exist in "r" mode raises a FileNotFoundError and crashes your program. The safe approach is to check whether the file exists first using os.path.exists().
import os
filename = "report.txt"
# Safe check before opening
if os.path.exists(filename):
with open(filename, "r") as file:
print(file.read())
else:
print(f"'{filename}' does not exist. Creating it now...")
with open(filename, "w") as file:
file.write("New report created.\n")
print("File created.")
File created.
What just happened?
os.path.exists(filename)returnsTrueif the file is there,Falseif not — no crash either way.- The program handles both cases gracefully: read the file if it exists, or create it if it does not.
- This pattern is used in every application that reads config files, user data, or cached results at startup.
8. Writing Multiple Lines with writelines()
When you have a list of strings you want to save to a file, writelines() writes them all at once — cleaner than calling write() in a loop.
# A list of items to save
shopping_list = [
"Apples\n",
"Bread\n",
"Milk\n",
"Eggs\n",
"Butter\n"
]
# Write all lines at once
with open("shopping.txt", "w") as file:
file.writelines(shopping_list)
# Read back to verify
with open("shopping.txt", "r") as file:
print(file.read())
Bread
Milk
Eggs
Butter
What just happened?
writelines()writes every string in the list to the file one after another — no separator is added automatically, so each string needs its own\n.- This is faster and cleaner than looping and calling
write()for each item separately. - Use
writelines()when your data is already in a list — usewrite()when you are building the content one piece at a time.
9. Working with CSV Files
CSV (Comma-Separated Values) is the most common format for storing and exchanging tabular data — spreadsheets, sales reports, user exports. Python's built-in csv module makes reading and writing CSV files simple and reliable.
import csv
# --- WRITE a CSV file ---
employees = [
["Name", "Department", "Salary"],
["Alice", "Engineering", 95000 ],
["Bob", "Marketing", 72000 ],
["Carol", "Design", 80000 ],
["David", "Engineering", 105000 ]
]
with open("employees.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(employees) # writes all rows at once
print("CSV written.")
# --- READ the CSV file ---
with open("employees.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
['Name', 'Department', 'Salary']
['Alice', 'Engineering', '95000']
['Bob', 'Marketing', '72000']
['Carol', 'Design', '80000']
['David', 'Engineering', '105000']
What just happened?
csv.writer(file)creates a writer object.writer.writerows()writes every row in the list to the file, automatically adding commas between values.newline=""in the open call is required on Windows to prevent blank lines appearing between rows in the CSV.csv.reader(file)reads the CSV back, returning each row as a list of strings. Notice that numbers become strings — cast them withint()orfloat()when you need to calculate with them.
10. CSV with DictReader and DictWriter
DictReader and DictWriter let you work with CSV rows as dictionaries — each row becomes {"column_name": "value"}. This is much easier to read and work with than plain lists, especially when CSV files have many columns.
import csv
# Write with DictWriter — column names are defined upfront
products = [
{"name": "Laptop", "price": 1200, "stock": 15},
{"name": "Monitor", "price": 450, "stock": 30},
{"name": "Keyboard","price": 80, "stock": 100}
]
with open("products.csv", "w", newline="") as file:
fields = ["name", "price", "stock"]
writer = csv.DictWriter(file, fieldnames=fields)
writer.writeheader() # writes the column name row
writer.writerows(products) # writes all data rows
# Read with DictReader — each row is a dictionary
with open("products.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
price = float(row["price"])
print(f" {row['name']:<12} ${price:.2f} (Stock: {row['stock']})")
Monitor $450.00 (Stock: 30)
Keyboard $80.00 (Stock: 100)
What just happened?
DictWriterwrites each dictionary as a row — thefieldnameslist sets the column order, andwriteheader()writes the column names as the first row.DictReaderreads each row as a dictionary —row["price"]is much clearer thanrow[1], especially in files with many columns.- Values from CSV are always strings —
float(row["price"])converts the price string to a number so we can format it properly.
11. Real-World Example — Write and Analyse a Sales Report
This program writes a sales report to a CSV file and then reads it back to calculate totals and find the top-selling product — exactly what a real business script would do.
import csv
# Sales data
sales = [
{"product": "Laptop", "units": 12, "price": 1200},
{"product": "Monitor", "units": 25, "price": 450},
{"product": "Keyboard", "units": 80, "price": 80},
{"product": "Webcam", "units": 40, "price": 120},
{"product": "Headset", "units": 30, "price": 150}
]
# Step 1: write the report to a CSV file
with open("sales_report.csv", "w", newline="") as file:
fields = ["product", "units", "price"]
writer = csv.DictWriter(file, fieldnames=fields)
writer.writeheader()
writer.writerows(sales)
# Step 2: read back and analyse
total_revenue = 0
top_product = ""
top_revenue = 0
with open("sales_report.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
revenue = int(row["units"]) * float(row["price"])
total_revenue += revenue
if revenue > top_revenue:
top_revenue = revenue
top_product = row["product"]
print(f"Total Revenue : ${total_revenue:,.2f}")
print(f"Top Product : {top_product} (${top_revenue:,.2f})")
Top Product : Monitor ($11,250.00)
What just happened?
- Step 1 wrote the full sales data to a CSV file — this is how a real program would save a daily or weekly report.
- Step 2 read the file back and calculated the total revenue by multiplying units × price for every row, then tracked which product had the highest revenue.
${total_revenue:,.2f}formats the number with commas and two decimal places — the standard way to display dollar amounts in Python.
12. Lesson Summary
| Concept | Syntax / Example | What It Does |
|---|---|---|
| Open a file | open("file.txt", "r") | Opens file in given mode |
| Safe open | with open(...) as f: | Auto-closes file when done |
| Write text | file.write("text\n") | Writes a string to the file |
| Write list | file.writelines(list) | Writes all strings in a list |
| Read all | file.read() | Returns entire file as a string |
| Read one line | file.readline() | Reads next line each call |
| Read all lines | file.readlines() | Returns list of all lines |
| Loop file | for line in file: | Memory-efficient line iteration |
| Append mode | open("f.txt", "a") | Adds to end without overwriting |
| Check exists | os.path.exists(filename) | Returns True if file exists |
| CSV write | csv.writer / DictWriter | Writes rows to a CSV file |
| CSV read | csv.reader / DictReader | Reads rows from a CSV file |
🧪 Practice Questions
Answer based on what you learned in this lesson.
1. Which file mode creates a new file and overwrites it if it already exists?
2. Which file mode adds content to the end of a file without deleting existing content?
3. What keyword is used to open a file safely so it closes automatically?
4. Which string method removes the \n newline character from the end of a line?
5. Which CSV class reads each row as a dictionary with column names as keys?
🎯 Quiz — Test Your Understanding
Q1. What error does Python raise when you try to open a file that does not exist in "r" mode?
Q2. What happens to an existing file when you open it with mode "w"?
Q3. Which method returns all lines of a file as a Python list?
Q4. What argument prevents blank lines appearing between CSV rows on Windows?
Q5. What is the most memory-efficient way to read a large file line by line?