Day 14: File Handling in Python
File handling is a fundamental concept in Python that allows programs to store and retrieve data from files. Unlike variables, which store data temporarily in memory, files help persist data permanently.
Why File Handling is Important
File handling is widely used in real-world applications. It helps in:
- Saving user data (such as login systems)
- Storing logs for debugging and monitoring
- Working with datasets in data science
- Reading configuration files for applications
Types of Files in Python
Python mainly works with two common types of files:
1. Text Files (.txt)
These store plain text data and are human-readable.
2. CSV Files (.csv)
CSV stands for Comma Separated Values and is used to store structured data in tabular form.
File Modes in Python
When working with files, Python provides different modes:
- r → Read file
- w → Write file (overwrites existing content)
- a → Append data to file
- r+ → Read and write
Opening and Closing Files
Basic syntax:
file = open("example.txt", "w")
file.write("Hello, this is Day 14 of Python Bootcamp\n")
file.close()
A better and recommended approach is using the with statement:
with open("example.txt", "r") as f:
content = f.read()
print(content)
This automatically handles closing the file.
Working with Text Files
Writing to a File
with open("example.txt", "w") as f:
f.write("Learning File Handling\n")
Appending Data
with open("example.txt", "a") as f:
f.write("Adding new content\n")
Reading Entire File
with open("example.txt", "r") as f:
content = f.read()
print(content)
Reading Line by Line
with open("example.txt", "r") as f:
for line in f:
print(line.strip())
Reading All Lines into a List
with open("example.txt", "r") as f:
content = f.readlines()
print(content)
File Pointer Concepts
Python maintains a pointer to track the current position in the file.
f.tell() # gives current position
f.seek(0) # moves pointer to beginning
Working with CSV Files
CSV files are used to store tabular data. Python provides the csv module to handle them efficiently.
Writing CSV Data
import csv
data = [
["Name","Age","City"],
["Piyush","21","Gangtok"],
["Rahul","22","Mumbai"]
]
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
Reading CSV Data
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Using DictReader
with open("data.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["Name"], row["Age"])
Writing CSV using Dictionary
import csv
data = [
{"Name":"Aman","Age":30},
{"Name":"Rohan","Age":23}
]
with open("data.csv", "w", newline="") as f:
fieldnames = ["Name","Age"]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
Common Errors in File Handling
- FileNotFoundError: Occurs when file does not exist
- Using wrong mode: For example, trying to read in write mode
- Forgetting to close file (if not using with)
Real-Life Example
Taking user input and storing it in a CSV file:
import csv
n = int(input("How many entries do you want to add?"))
data = []
for i in range(n):
print(f"\nEnter details for person {i+1}")
name = input("Enter name: ")
age = input("Enter age: ")
city = input("Enter city: ")
data.append([name, age, city])
with open("person.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name","Age","City"])
writer.writerows(data)
print("Data successfully written to person.csv")
Assignment Questions
Basic Level
- Create a text file and write 5 lines into it.
- Read a text file and print its content.
- Append a new line to an existing file.
- Read a file line by line and print each line.
Intermediate Level
- Count the number of words in a text file.
- Count how many lines are present in a file.
- Read a file and print only lines that contain a specific word.
- Use seek() and tell() to demonstrate file pointer movement.
CSV Based Questions
- Create a CSV file with student details (Name, Marks, City).
- Read the CSV file and display all records.
- Print students who have marks greater than 80.
- Use DictReader to access specific columns.
Advanced Level
- Take user input and store it in a CSV file.
- Convert a text file into CSV format.
- Build a small program to search for a student in a CSV file.
Conclusion
File handling is a critical concept in Python that enables real-world application development. From saving user data to working with datasets, mastering file operations is essential for any developer, especially in data science and backend development.
.png)

0 Comments:
Post a Comment