File Handling in Python
CSN12601 – AI & ML Lab
Department of Computer Science and Engineering
MNNIT Allahabad
1. Introduction 4. List vs Set (Very Impor-
In Python, file handling allows us to: tant)
• Store data permanently List
• Read datasets for AI/ML • Ordered
• Process images and structured data • Allows duplicates
• Share data between programs
Memory (RAM) → Temporary numbers = [1, 2, 2, 3]
File (Disk) → Permanent
Set
2. Opening a File A set:
Python uses the open() function: • Unordered
• Stores only unique elements
file = open("[Link]", "mode")
numbers = {1, 2, 2, 3}
print(numbers)
File Modes
• ’r’ → Read Output:
• ’w’ → Write (overwrites)
• ’a’ → Append {1, 2, 3}
• ’rb’ → Read Binary
• ’wb’ → Write Binary Why duplicates removed? Because
mathematically, a set cannot contain repeated
elements.
3. Best Practice: with
Statement 5. Using set() to Remove
Automatically closes file. Duplicates
with open("[Link]", "r") as f: my list = [1,2,2,3]
content = [Link]() unique = set(my list)
print(content) print(unique)
1
6. Sorting Data using Correct method:
sorted() with open("[Link]","rb") as
sorted(): src:
data = [Link]()
• Takes list/set with open("[Link]","wb") as dst:
• Returns sorted list [Link](data)
names = ["Rahul", "Ankit", "Zoya"]
print(sorted(names))
10. Exception Handling
Sorting numbers:
Common errors:
nums = {5,1,8,2}
print(sorted(nums)) • FileNotFoundError
• ModuleNotFoundError
7. Removing Punctuation Example:
Used when cleaning text files. try:
with open("[Link]","r") as f:
import string content = [Link]()
text = "Hello, world!" except FileNotFoundError:
clean = [Link]( print("File not found!")
[Link](’’, ’’,
[Link]))
print(clean)
11. Directory Awareness
Removes: .,!?;:'” etc. (Jupyter – Ubuntu)
Check current directory:
8. Text File Copying
import os
For text files (.txt, .csv): print([Link]())
with open("[Link]","r") as
List files:
src:
data = [Link]()
print([Link]())
with open("[Link]","w") as dst:
[Link](data)
Most file errors occur because file is not in
current directory.
9. Binary File Copying
(Images) 12. Relative vs Absolute
Images are binary files. Path
Why ’rb’ and ’wb’ ?
• "[Link]" → Same folder
• Text mode reads characters • "./folder/[Link]" → Inside folder
• Images contain binary data • "/home/user/[Link]" → Absolute
• Wrong mode can corrupt file path
2
13. Working with File For- pip install pandas openpyxl
mats
In AI/ML, data may come in structured,
(d) Text Files (.txt)
semi-structured, or binary formats. Python Text files are handled using the built-in
provides different libraries for handling each open() function.
type.
with open("[Link]", "r") as
file:
(a) CSV Files (.csv) content = [Link]()
print(content)
CSV (Comma Separated Values) files store
tabular data. Python provides a built-in csv
module. (e) JPG Files (.jpg)
import csv Images are binary files. We use the PIL (Pil-
with open("[Link]", "r") as file: low) library.
reader = [Link](file)
for row in reader: from PIL import Image
print(row) img = [Link]("[Link]")
print("Format:", [Link])
Each row is returned as a list of values. print("Size:", [Link])
print("Mode:", [Link])
(b) TSV Files (.tsv) Why binary?
Images are not text. They contain pixel
TSV (Tab Separated Values) files are similar data stored in binary format. Therefore,
to CSV, but values are separated by a tab copying images requires ’rb’ and ’wb’
instead of comma. modes.
If Pillow is not installed:
import csv
with open("[Link]", "r") as file: pip install pillow
reader = [Link](file,
delimiter=’
t’) 14. Practice Problems
for row in reader:
print(row) 1. Create a file and write 5 lines. Read and
display them.
Note: ’\t’ represents a tab character. 2. Create a list with duplicates. Convert to
set and print unique values.
3. Sort a list of names alphabetically.
(c) Excel Files (.xlsx) 4. Read a sentence from file, remove punc-
Excel files are commonly used for datasets. tuation and convert to lowercase.
We use the pandas library. 5. Copy a text file to another file.
6. Check current directory and list all files.
import pandas as pd 7. Try opening a non-existing file and han-
data = [Link] excel("[Link]") dle the error.
print([Link]())
Important: If you get
ModuleNotFoundError, install using: