Python Reading & Writing Files
read() / write() / append()Practice

Practical file operations

Learn to work with files: reading entire files, processing line-by-line, appending data, and writing results. Perfect for data processing and logging tasks.

Picture this: write a line, then read it back

Mode 'w' writes (creates/overwrites). Mode 'r' reads.

text in Pythona string
→
write to diskf.write
→
read from diskf.read
→
string againin memory

In easy words: What will you do?

You'll read text from a file, process it (count lines, search for keywords, transform data), and write results to a new file. This is a core pattern: input → process → output.

Where this is used

Used in data analysis (CSV files), log processing, text filtering, creating reports, batch file renaming, extracting data from large documents, and any ETL (Extract-Transform-Load) task.

Real world: student grades

A file contains "Alice: 95, Bob: 87, Carol: 92". Your program reads it, calculates average grade, writes a report "Average: 91.3 pass: 3". All data comes from and goes to disk.

Reading a file completely

Read entire file

📁 Input file: grades.txt
Alice: 95 Bob: 87 Carol: 92 David: 88
1with open("grades.txt", "r") as file:
2content = file.read()
3print(content)
📤 Output (console)
Alice: 95 Bob: 87 Carol: 92 David: 88
Reading line-by-line

Process each line

📁 Input file: grades.txt
Alice: 95 Bob: 87 Carol: 92 David: 88
1with open("grades.txt", "r") as file:
2for line in file:
3name, grade = line.strip().split(":")
4print(f"{name.strip()} = {int(grade)}")
📤 Output (console)
Alice = 95 Bob = 87 Carol = 92 David = 88
Writing to a file

Create output file

1with open("output.txt", "w") as file:
2file.write("Grade Report\n")
3file.write("=" * 30 + "\n")
4file.write("Average: 90.5\n")
📁 Created file: output.txt
Grade Report ============================== Average: 90.5
Appending to a file

Add to existing file

📁 File before (output.txt)
Grade Report ============================== Average: 90.5
1with open("output.txt", "a") as file:
2file.write("\nPassed: 4/4")
📁 File after (output.txt)
Grade Report ============================== Average: 90.5 Passed: 4/4
Common patterns
Count lines Open file, iterate lines, count them. Useful for file size checks.
Search keyword Read each line, check if word exists. Find all matching lines.
Transform data Read → modify → write. Perfect for batch processing.
Merge files Read from 2+ files, write combined output to new file.

File reading methods

1content = file.read() # all at once (entire file)
2lines = file.readlines() # list of lines
3one_line = file.readline() # next line only
4for line in file: # loop best for large files

Example Program: Grade Processor

1# Read grades, calculate average, write report
2grades = []
3with open("grades.txt", "r") as f:
4for line in f:
5name, grade = line.strip().split(":")
6grades.append(int(grade))
7avg = sum(grades) / len(grades)
8with open("report.txt", "w") as f:
9f.write(f"Average: {avg:.1f}")