Python File Handling
-CSV/Binary
CSV File Handling Programs
1.Write rows to CSV
import csv
f = open("[Link]", "w", newline="")
w = [Link](f)
[Link](["ID", "Name", "Age"])
[Link]([1, "Alice", 20])
[Link]([2, "Bob", 22])
[Link]()
2.Read entire CSV
import csv
f = open("[Link]", "r")
r = [Link](f)
for row in r:
print(row)
[Link]()
3.Append new row
import csv
f = open("[Link]", "a", newline="")
w = [Link](f)
[Link]([3, "Charlie", 25])
[Link]()
4.Read specific column
import csv
f = open("[Link]", "r")
r = [Link](f)
for row in r:
print(row[1]) # print Name column
[Link]()
5.Count rows
import csv
f = open("[Link]", "r")
r = [Link](f)
count = 0
for row in r:
count += 1
print("Total rows:", count)
[Link]()
6.Write multiple rows
import csv
f = open("[Link]", "w", newline="")
w = [Link](f)
rows = [[101, "Tom"], [102, "Jerry"], [103, "Spike"]]
[Link](rows)
[Link]()
7.Check if a name exists
import csv
f = open("[Link]", "r")
r = [Link](f)
found = False
for row in r:
if "Alice" in row:
found = True
print("Found" if found else "Not Found")
[Link]()
8.Copy CSV file
import csv
f1 = open("[Link]", "r")
f2 = open("[Link]", "w", newline="")
r = [Link](f1)
w = [Link](f2)
for row in r:
[Link](row)
[Link]()
[Link]()
9.Filter rows by condition
import csv
f = open("[Link]", "r")
r = [Link](f)
for row in r:
if row[0].isdigit() and int(row[0]) > 1:
print(row)
[Link]()
10. Read with DictReader
import csv
f = open("[Link]", "r")
r = [Link](f)
for row in r:
print(row["Name"], row["Age"])
[Link]()
Binary File Handling Programs
using pickle
1.Write a list into a binary file
import pickle
f = open("[Link]", "wb")
data = [1, 2, 3, 4, 5]
[Link](data, f)
[Link]()
2.Read list from a binary file
import pickle
f = open("[Link]", "rb")
data = [Link](f)
print(data)
[Link]()
3.Write a dictionary
import pickle
f = open("[Link]", "wb")
student = {"id": 101, "name": "Alice", "marks": 88}
[Link](student, f)
[Link]()
4.Read a dictionary
import pickle
f = open("[Link]", "rb")
student = [Link](f)
print(student)
[Link]()
5.Write multiple objects
import pickle
f = open("[Link]", "wb")
[Link]("Hello", f)
[Link]([10, 20, 30], f)
[Link]({"x": 5, "y": 10}, f)
[Link]()
6.Read multiple objects
import pickle
f = open("[Link]", "rb")
print([Link](f))
print([Link](f))
print([Link](f))
[Link]()
7.Append object to file
import pickle
f = open("[Link]", "ab")
[Link]("New Data", f)
[Link]()
8.Write list of student records
import pickle
f = open("[Link]", "wb")
records = [
{"id": 1, "name": "A"},
{"id": 2, "name": "B"},
{"id": 3, "name": "C"}
]
[Link](records, f)
[Link]()
9.Read list of student records
import pickle
f = open("[Link]", "rb")
records = [Link](f)
for r in records:
print(r["id"], r["name"])
[Link]()
10. Search a record in binary file
import pickle
f = open("[Link]", "rb")
records = [Link](f)
roll = 2
found = False
for r in records:
if r["id"] == roll:
print("Found:", r)
found = True
if not found:
print("Not Found")
[Link]()