Revision Notes for CSV File Handling in Python(Class 12 Computer Science)
Revision Notes for CSV File Handling in Python. This topic is part of the File Handling Unit and usually carries 3-5 Marks (often a coding question).
1. What is a CSV File?
Full Form: Comma Separated Values.
Nature: It is a standard Text File.
Structure: Stores tabular data (rows and columns) in plain text form.
Default Delimiter: Comma (
,).Module Required:
import csv
2. The Golden Rule: Opening a CSV File
When opening a CSV file, you MUST use the argument newline=''.
Why? In Windows, Python converts
\nto\r\nautomatically. If you don't usenewline='', your CSV file will have blank lines between every row.Syntax:
Pythonf = open("data.csv", "w", newline='')
3. Writing to a CSV File
You need a Writer Object.
Steps:
Open file in
'w'(Write) or'a'(Append) mode.Create a writer object:
wo = csv.writer(file_handle).Write data using methods.
Methods:
writerow(list): Writes a single row (takes a list).writerows(nested_list): Writes multiple rows at once (takes a list of lists).
Code Pattern:
import csv
data = ["Roll", "Name", "Marks"]
row1 = [101, "Amit", 95]
with open("student.csv", "w", newline='') as f:
wo = csv.writer(f)
wo.writerow(data) # Writing Header
wo.writerow(row1) # Writing Single Record
# OR
# wo.writerows([data, row1])
4. Reading from a CSV File
You need a Reader Object.
Steps:
Open file in
'r'(Read) mode.Create a reader object:
ro = csv.reader(file_handle).Iterate through the reader object (it acts like a list of rows).
Key Concept:
csv.readerreturns data as a List of Strings.Example: Even if the file has
101, Python reads it as'101'. You must typecast it tointif doing calculations.
Code Pattern:
import csv
with open("student.csv", "r") as f:
ro = csv.reader(f)
for row in ro:
# row is a list, e.g., ['101', 'Amit', '95']
print(row[0], row[1])
5. Custom Delimiters
Sometimes CSV files use a separator other than a comma (like a tab or a pipe |).
Syntax: Pass
delimiterargument.Pythonreader = csv.reader(f, delimiter='\t') # For Tab separated writer = csv.writer(f, delimiter='|') # For Pipe separated
6. Exam Cheat Sheet: Common Coding Questions
Scenario A: Create a CSV file (Taking User Input)
import csv
def create_csv():
f = open("inventory.csv", "w", newline='')
wo = csv.writer(f)
wo.writerow(["ID", "Product", "Price"]) # Header
while True:
pid = int(input("ID: "))
name = input("Name: ")
price = float(input("Price: "))
wo.writerow([pid, name, price])
ch = input("More? (y/n): ")
if ch == 'n': break
f.close()
Scenario B: Search and Display logic
Question: Display products with Price > 500.
import csv
def search_csv():
f = open("inventory.csv", "r")
ro = csv.reader(f)
next(ro) # OPTIONAL: Skips the header row
for row in ro:
# row[2] is the price, but it is a String!
if float(row[2]) > 500:
print(row)
f.close()
7. Common Syllabus Errors (Don't do these!)
Forgetting
newline='': Result = Empty lines in output file.Forgetting Typecasting:
row[2] > 500will cause an error becauserow[2]is a string'900'. You must compareint(row[2]) > 500.Mixing Syntax: Using
pickle.load()on a CSV file. (Wrong! Usecsv.reader).
Comments
Post a Comment