Tuesday, 21 April 2026

April Python Bootcamp Day 14


 

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

  1. Create a text file and write 5 lines into it.
  2. Read a text file and print its content.
  3. Append a new line to an existing file.
  4. Read a file line by line and print each line.

Intermediate Level

  1. Count the number of words in a text file.
  2. Count how many lines are present in a file.
  3. Read a file and print only lines that contain a specific word.
  4. Use seek() and tell() to demonstrate file pointer movement.

CSV Based Questions

  1. Create a CSV file with student details (Name, Marks, City).
  2. Read the CSV file and display all records.
  3. Print students who have marks greater than 80.
  4. Use DictReader to access specific columns.

Advanced Level

  1. Take user input and store it in a CSV file.
  2. Convert a text file into CSV format.
  3. 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.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (248) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (29) Azure (10) BI (10) Books (262) Bootcamp (9) C (78) C# (12) C++ (83) Course (87) Coursera (300) Cybersecurity (30) data (5) Data Analysis (31) Data Analytics (22) data management (15) Data Science (347) Data Strucures (17) Deep Learning (154) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (70) Git (10) Google (51) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (42) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (286) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (14) PHP (20) Projects (32) pytho (1) Python (1315) Python Coding Challenge (1128) Python Mistakes (51) Python Quiz (482) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (49) Udemy (18) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)