File Handling in Python (Detailed)
What is a File?
A file is a collection of data stored on a computer's storage device (hard disk, SSD, etc.)
with a name and an extension.
• Files are used to store data permanently.
• When you run a Python/Java program, variables exist temporarily in RAM.
• But files ensure data is saved even after the program ends.
Examples in Real Life:
• Text file → notes.txt (Notepad, code files)
• Binary file → song.mp3, image.jpg
• CSV file → students.csv (Excel-like data)
• Log file → log.txt (QA testing reports)
Why Files are Needed?
• To store user data permanently
• To exchange data between applications (Excel, DB, APIs)
• To store logs in testing and automation
• To manage structured/unstructured data
Without files → Data lost when program ends.
With files → Data safe, can be reused.
Types of Files
In Python (and in general computing), files are mainly divided into 3 categories:
(a) Text Files (.txt, .log, .cfg, .py, etc.)
• Store plain human-readable text (characters, numbers, symbols).
• Data stored in lines.
• Can be opened with Notepad, VS Code, Sublime etc.
Example Content (notes.txt):
Hello Rupesh
Welcome to Python
This is a text file
Program Example:
# Writing into a text file
with open("notes.txt", "w") as f:
f.write("Hello Rupesh!\n")
f.write("This is a text file.\n")
# Reading from a text file
with open("notes.txt", "r") as f:
print(f.read())
Real Use: Logs, configs, test reports, chat history.
(b) Binary Files (.bin, .dat, .jpg, .mp3, .mp4, etc.)
• Store data in binary form (0s and 1s).
• Not human-readable.
• Used for images, audio, video, executables, ML models.
Program Example:
# Copying an image using binary mode
with open("photo.jpg", "rb") as f:
data = f.read()
with open("copy_photo.jpg", "wb") as f:
f.write(data)
print(" Image copied successfully.")
Real Use: Images, videos, games, ML model storage.
(c) CSV Files (.csv – Comma Separated Values)
• Store tabular data (rows & columns, like Excel).
• Each line = record (row).
• Fields separated by comma ( , ).
Example Content (students.csv):
Name, Age, Marks
Ravi, 20, 85
Sita, 22, 90
Aman, 21, 75
Program Example:
import csv
# Writing CSV
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age", "Marks"])
writer.writerow(["Ravi", 20, 85])
writer.writerow(["Sita", 22, 90])
# Reading CSV
with open("students.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Real Use: QA test data, Excel export/import, ML datasets, database migration.
Other File Types (extra knowledge)
• JSON file (.json): Used for APIs, configs.
• XML file (.xml): Used in web data and configs.
• Log files (.log): Store error/debug/test logs.
Summary
• File = Permanent data storage unit on computer.
• Text File → Human-readable (logs, configs, notes).
• Binary File → Not readable (images, videos, executables).
• CSV File → Structured, tabular data (Excel-like).
• Files make programs useful, reusable, and reliable.
1. What is File Handling?
File handling means storing data permanently in files (text, binary, CSV) and performing
operations like:
• Creating a file
• Reading data
• Writing/Updating data
• Closing file properly
Without file handling → Data will be lost once program ends.
With file handling → Data is saved permanently in hard disk.
2. File Types
1. Text File (.txt) → stores normal text.
2. Binary File (.bin, .dat) → stores data in binary form (images, audio, video).
3. CSV File (.csv) → comma-separated values, used for structured data like Excel.
Types of Files in Python
Text File (.txt)
What it is:
• Stores human-readable characters (letters, numbers, symbols).
• Example: Notepad files.
• Data is stored as plain text.
Operations:
• Create
• Write
• Read (full, line by line, all lines)
• Append
Example (Program):
# Writing to a text file
with open("notes.txt", "w") as f:
f.write("Hello Rupesh!\n")
f.write("This is a text file.\n")
f.write("You can read and write easily.")
# Reading from a text file
with open("notes.txt", "r") as f:
data = f.read()
print(" File Content:\n", data)
Real World Use:
• Log files (errors, transactions)
• Config files (.ini, .cfg)
• Chat history / Notepad
Binary File (.bin, .dat, images, audio, video)
What it is:
• Stores data in 0s and 1s (binary format).
• Not human-readable directly.
• Used for images, audio, video, executables, serialized objects.
Operations:
• Need to use "rb" (read binary), "wb" (write binary), "ab" (append binary).
• We can store Python objects using pickle module.
Example (Write and Read Binary Data):
# Writing binary data
with open("binarydata.bin", "wb") as f:
f.write(b"Hello, this is binary data!")
# Reading binary data
with open("binarydata.bin", "rb") as f:
data = f.read()
print(" Binary Data:", data)
Example with Image Copy:
# Copy an image using binary file handling
with open("input.jpg", "rb") as f:
img_data = f.read()
with open("output.jpg", "wb") as f:
f.write(img_data)
print(" Image copied successfully.")
Real World Use:
• Storing images, videos, audio
• Database files
• Machine Learning models (saved as .pkl)
CSV File (.csv – Comma Separated Values)
What it is:
• Stores tabular data (like Excel).
• Each row = record, Each column = field.
• Example:
• Name, Age, Marks
• Ravi, 20, 85
• Sita, 22, 90
• Aman, 21, 75
Why CSV?
• Lightweight, portable.
• Easy to import/export between Excel, Python, Databases.
Example (Write CSV):
import csv
# Writing CSV file
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age", "Marks"])
writer.writerow(["Ravi", 20, 85])
writer.writerow(["Sita", 22, 90])
writer.writerow(["Aman", 21, 75])
print(" CSV file created.")
Example (Read CSV):
import csv
# Reading CSV file
with open("students.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Output:
['Name', 'Age', 'Marks']
['Ravi', '20', '85']
['Sita', '22', '90']
['Aman', '21', '75']
Real World Use:
• Data exchange between applications
• Storing test cases / bug reports in QA
• Import/Export from Excel
• Machine Learning datasets
Key Differences: Text vs Binary vs CSV
Feature Text File (.txt) Binary File (.bin, .dat) CSV File (.csv)
Data Tabular (comma-
Human-readable text Raw binary (0s and 1s)
Storage separated)
Directly readable in
Readability Not human-readable Readable like Excel
Notepad
Example Images, audio, ML
Logs, configs, notes Structured data (tables)
Use models
File Mode "r", "w", "a" "rb", "wb", "ab" "r", "w", via csv module
Libraries No extra needed pickle for objects csv for structured data
Shortcut to remember:
• Text file → Simple notes
• Binary file → Media & objects
• CSV file → Tables & structured data
Relative Path vs Absolute Path
Absolute Path
Definition:
• The complete path of a file/folder starting from the root directory (C:\ in Windows, / in
Linux/Mac).
• It tells exact location of file in your computer, no matter from where you run the
program.
Always starts from root (C:/, D:/, /home/user/)
Example (Windows):
C:\Users\Rupesh\Documents\example.txt
Example (Linux/Mac):
/home/rupesh/Documents/example.txt
Real World Example:
• Jab tu Gmail me koi file attach karta hai, system uska absolute path dikhata hai.
• Example: C:\Users\Rupesh\Desktop\resume.pdf
Relative Path
Definition:
• The path relative to the current working directory (CWD).
• Matlab, file ka location program ke folder ke respect me diya jata hai.
• Short and flexible.
Doesn’t start with root → it starts from where your Python file is running.
Example:
If your Python script is in:
C:\Users\Rupesh\Projects\
and file is in:
C:\Users\Rupesh\Projects\data\example.txt
Relative Path would be:
data/example.txt
Real World Example:
• Jab tu project bana raha hai (like Selenium, Django, Java project), uske config files ko
relative path se access karta hai so that project runs on any PC without changing file
locations.
Python Example
import os
# Absolute Path Example
absolute_path = "C:/Users/Rupesh/Documents/example.txt"
with open(absolute_path, "w") as f:
f.write("This is absolute path example.")
# Relative Path Example
relative_path = "data/example.txt" # folder "data" must exist in same dir
os.makedirs("data", exist_ok=True) # create folder if not exists
with open(relative_path, "w") as f:
f.write("This is relative path example.")
print(" File created with absolute and relative paths.")
Key Differences:
Feature Absolute Path Relative Path
Starts From Root directory (C:/, /, etc.) Current working directory
Flexibility Fixed → same everywhere Flexible → depends on project dir
Example C:/Users/Rupesh/Documents/file.txt docs/file.txt
Use Case Sharing exact file location in system Inside projects, portable coding
Shortcut to Remember:
• Absolute path → “Full GPS Address” 🗺
• Relative path → “Shortcut from where you are standing”