csv files
csv files
BINARY FILES-
# Write a program that reads a csv file and creates
another csv file with the same content except the
lines with “hello”-
import csv
row_list=[["S.NO", "Name","Contribution"],
[1., "Hello", "Linux Kernel"],
[2., "Tim Berners-Lee", "World Wide Web"]]
with open("C:\\Users\\kashish\\Desktop\\
Program3.csv","w",newline="") as file:
write=csv.writer(file)
write.writerows(row_list)
import csv
reader=csv.reader(open("C:\\Users\\Kashish\\Desktop\\
Program3.csv",'r'))
writer=csv.writer(open("C:\\Users\\kashish\\Desktop\\
Program4.csv",'w'))
for i in reader:
for j in i:
if j=="Hello":
continue
else:
writer.writerow(i)
#Reading and writing csv file as list-
import csv
f=open("file.csv","a",newline='') #opens file in append mode
cw=csv.writer(f) #cw links fileobject with csv module writer
ans='y'
while ans=='y':
l=[]
roll=int(input("enter roll"))
nm=input("name")
l.append(roll)
l.append(nm)
m=[]
for i in range(0,3):
x=float(input("enter marks"))
m.append(x)
l.append(m)
cw.writerow(l)#using cw now we can write to csv file using writerow method
ans=input("enter y/n")
f.close()
f=open("file.csv","r")
cr=csv.reader(f) # cr links with csv module reader
for line in cr:
print(line)
f.close()
#Writing a dictionary-
import csv
csv_columns = ['No','Name','Country']
dict_data = [
{'No': 1, 'Name': 'Alex', 'Country': 'India'},
{'No': 2, 'Name': 'Ben', 'Country': 'USA'},
{'No': 3, 'Name': 'Shri Ram', 'Country': 'India'},
{'No': 4, 'Name': 'Smith', 'Country': 'USA'},
{'No': 5, 'Name': 'Yuva Raj', 'Country': 'India'},
]
csv_file = "dictfile.csv"
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for data in dict_data:
writer.writerow(data)
except IOError:
print("I/O error")
'''
a_file = open("sample.csv", "w")
a_dict = {"a": 1, "b": 2}
writer = csv. writer(a_file)
for key, value in a_dict. items():
writer. writerow([key, value])
a_file. close()
'''
# Write a program that write a nested python list to
a csv file. After writing csv file read the csv file and
display the content in tabular format-
import csv
filename="C:\\Users\kashish\\Desktop\\program1.csv"
fields=[]
rows=[]
with open(filename,'r') as csvfile:
csvreader=csv.reader(csvfile)
fields=next(csvreader)
for row in csvreader:
rows.append(row)
print("Total no of rows: %d"%(csvreader.line_num))
print('\n')
print('\t '.join(field for field in fields))
for row in rows[:5]:
for col in row:
print(col,end=" ")
print('\n')
#Create a pickled file called ‘colony.dat’ containing the details of
a colony. The tructure of a colony is as☹ colony_code string,
colony_name string, no_of_people int)Write a function in python
to update the file with a new value of no_of_people as per their
colony_code. The value of colony_code and no_of_people are read
during the execution of the program-
import pickle
def insertRec():
file=open('C:\\Users\\kashish\\Desktop\\Colony.dat','wb')
for i in range(3):
Colony_Code=input("Enter Colony Code")
Colony_Name=input("Enter Colony Name")
No_Of_People=int(input("Enter No_of People"))
dic={'Colony_Code':Colony_Code,'Colony_Name':Colony_Name,'No of
People':No_Of_People}
pickle.dump(dic,file)
file.close()
def updateRecord():
import pickle
Colony_Code=input("Enter Colony Code")
No_Of_People=int(input("Enter No_of People"))
file=open('C:\\Users\\kashish\\Desktop\\Colony.dat','rb')
data=[]
while True:
try:
text=pickle.load(file)
data.append(text)
except EOFError:
pass
file.close()
for i in range(len(data)):
if data[i]['Colony_Code']==Colony_Code:
data[i]['No of People']=No_Of_People
file=open('C:\\Users\\kashish\\Desktop\\Colony.dat','wb')
for i in data:
pickle.dump(i,file)
file.close()
def readRecord():
import pickle
file=open('C:\\Users\\kahsish\\Desktop\\Colony.dat','rb')
while True:
try:
text=pickle.load(file)
print(text['Colony_Code'])
print(text['Colony_Name'])
print(text['No Of People'])
except EOFError:
pass
file.close()
# Consider a binary file’student.dat’ which contains
the records of students such as name, rollno, class
and marks. Write a program in python to print the
records of only those students from the file who score
marks greater than 60%. import pickle-
Import pickle
def count rec():
f=open("student.dat","rb")
num=0
try:
while true:
rec=pickle.load(f)
if rec[3]>60:
print(rec[0],rec[1],rec[2],rec[3])
num+=1
except:
f.close()
return num
# Create a file “sports.dat” contains information in
following format: Event- Participant.Write a function
in python that would read contents from file
sports.dat and creates a file named Atheletic .dat
copying only those records from sports.dat where the
event name is ‘Atheletics’.
#Write a Python program to write a Python dictionary
to a csv file. After writing the CSV file read the CSV file
and display the content.-
import csv
csv_columns = ['id','Column1', 'Column2', 'Column3', 'Column4', 'Column5']
dict_data = {'id':['1', '2', '3'],
'Column1':[33, 25, 56],
'Column2':[35, 30, 30],
'Column3':[21, 40, 55],
'Column4':[71, 25, 55],
'Column5':[10, 10, 40], }
csv_file = "temp.csv"
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for data in dict_data:
writer.writerow(dict_data)
except IOError:
print("I/O error")
data = csv.DictReader(open(csv_file))
print("CSV file as a dictionary:\n")
for row in data:
print(row)
#Write a Python program to write a Python list of lists
to a csv file. After writing the CSV file read the CSV file
and display the content-
import csv
data = [[10,'a1', 1], [12,'a2', 3], [14, 'a3', 5], [16, 'a4', 7], [18, 'a5', 9]]
with open("temp.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
with open('temp.csv', newline='') as csvfile:
data = csv.reader(csvfile, delimiter=' ')
for row in data:
print(', '.join(row))
#Write a Python program to create an object for
writing and iterate over the rows to print the values-
import csv
import sys
with open('temp.csv', 'wt') as f:
writer = csv.writer(f)
writer.writerow(('id1', 'id2', 'date'))
for i in range(3):
row = (
i + 1,
chr(ord('a') + i),
'01/{:02d}/2019'.format(i + 1),)
writer.writerow(row)
print(open('temp.csv', 'rt').read())
#Write a Python program that reads each row of a
given csv file and skip the header of the file. Also print
the number of rows and the field names-
import csv
fields = []
rows = []
with open('departments.csv', newline='') as csvfile:
data = csv.reader(csvfile, delimiter=' ', quotechar=',')
# Following command skips the first row of the CSV file.
fields = next(data)
for row in data:
print(', '.join(row))
print("\nTotal no. of rows: %d"%(data.line_num))
print('Field names are:')
print(', '.join(field for field in fields))
#Write a Python program to read specific columns of
a given CSV file and print the content of the columns-
import csv
with open('departments.csv', newline='') as csvfile:
data = csv.DictReader(csvfile)
print("ID Department Name")
print("---------------------------------")
for row in data:
print(row['department_id'], row['department_name']
#Write a Python program that reads a CSV file and
remove initial spaces, quotes around each entry and
the delimiter-
import csv
csv.register_dialect('csv_dialect',
delimiter='|',
skipinitialspace=True,
quoting=csv.QUOTE_ALL)
with open('temp.csv', 'r') as csvfile:
reader = csv.reader(csvfile, dialect='csv_dialect')
for row in reader:
print(row)
#Write a Python program to read each row from a
given csv file and print a list of strings-
import csv
with open('departments.csv', newline='') as csvfile:
data = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in data:
print(', '.join(row))
#WRITING TO A CSV FILE-
# importing the csv module
import csv
# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']
# data rows of csv file
rows = [ ['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']]
# name of csv file
filename = "university_records.csv"
# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
# writing the fields
csvwriter.writerow(fields)
# writing the data rows
csvwriter.writerows(rows)