Python File Handling
Introduction to File Handling
File handling allows you to read from and write to files on disk. Python provides built-in open()
function for this.
Common modes: r
(read), w
(write), a
(append).
Reading Files
Use open
and read()
/readlines()
to fetch content.
# Example: Reading list of Indian states from states.txt with open('states.txt', 'r', encoding='utf-8') as f: states = [line.strip() for line in f.readlines()] print(states)
Writing Files
Use w
or a
mode to write or append.
# Example: Writing train ticket info to file tickets = ['PNR: 1234567890 - Name: Rahul Kumar', 'PNR: 9876543210 - Name: Priya Singh'] with open('tickets.txt', 'w', encoding='utf-8') as f: for t in tickets: f.write(t + ' ')
Working with CSV
Use csv
module to parse and write CSV files.
import csv # Read student marks from CSV with open('students.csv', newline='', encoding='utf-8') as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(f"{row['Name']} scored {row['Marks']}") # Write new data fields = ['Name','Marks'] rows = [{'Name':'Anjali','Marks':88},{'Name':'Vikram','Marks':92}] with open('results.csv','w', newline='', encoding='utf-8') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fields) writer.writeheader() writer.writerows(rows)