CSV file handling
CSV file handling
CSV file handling
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
Example code:
import csv
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['John', 25, 'New York'])
7. Common Operations
● Count Records:
○ Iterate through rows and count.
● Search Data:
○ Compare field values while reading rows.
● Perform Calculations:
○ Sum specific fields like salary.
9. Key Points
● Use the appropriate delimiter if the CSV uses characters other than commas.
● Handle exceptions for missing files or incorrect formats.
import csv
writer = csv.writer(file)
while True:
break
reader = csv.reader(file)
data = list(reader)
break
else: