0% found this document useful (0 votes)
277 views

CSV Cheatsheet

This document provides an overview of algorithms for reading from and writing to CSV files in Python. It includes: 1. How to import the CSV module and open a CSV file in reading mode to load data into a list object for processing. 2. How to write data to a CSV file by opening it in writing mode, initializing a writer object, and using the writerow method to insert rows. 3. An example of adding multiple rows to a CSV file by prompting for input and writing each row with writerow inside a loop.

Uploaded by

Aircc Airccse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
277 views

CSV Cheatsheet

This document provides an overview of algorithms for reading from and writing to CSV files in Python. It includes: 1. How to import the CSV module and open a CSV file in reading mode to load data into a list object for processing. 2. How to write data to a CSV file by opening it in writing mode, initializing a writer object, and using the writerow method to insert rows. 3. An example of adding multiple rows to a CSV file by prompting for input and writing each row with writerow inside a loop.

Uploaded by

Aircc Airccse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

CHEATSHEETS FOR CSV FILE

ALGORITHM FOR READING IN CSV FILE READING IN CSV FILE WRITING IN CSV FILE
1. Import csv module from csv import reader from csv import writer
import csv f = open("cust.csv","r") f = open("students.csv","w")
2. Open the csv file in reading mode dt = reader(f) dt = writer(f)
f = open(“demo.csv”,”r”) data = list(dt) dt.writerow(['No','Name','Mark'])
3. Use list object to store the data read from f.close() f.close()
csv using reader for i in data:
data = csv.reader(f) for j in i: Insert multiple rows in the csv file
4. close the csv file print(j) from csv import writer with
f.close() print(end=" ") open("cust.csv","a",newline="\n") as f:
5. print the data object dt = writer(f)
print(data)
while True:
Delete a row from csv file
sno= int(input("Enter Serial No:"))
import csv
cname = input("Enter name:")
record = list()
city = input("Enter city:")
custname= input("Please enter a customer name to delete:")
amt = int(input("Enter amount:"))
with open('cust.csv', 'r') as f: dt.writerow([sno, cname, city, amt])
data = csv.reader(f) print("Record has been added.")
for row in data: print("Want to add? Type YES!!!")
record.append(row) ch = input()
for field in row: ch = ch.upper()
if field == custname: if ch=="YES":
record.remove(row) print("********************")
with open('cust.csv', 'w') as f: else:
writer = csv.writer(f) break
writer.writerows(record)

You might also like