Page 151 - PYTHON-12
P. 151
12. Write a Python program to read specific columns from a "department.csv" file and print the content of
the columns, department id and department name.
Ans. import csv
with open('departments.csv', newline='') as csvfile:
data = csv.reader(csvfile)
print("ID Department_Name")
print("---------------------------------")
for row in data:
print(row[0], row[1])
13. Explain briefly the CSV format of storing files.
Ans. The acronym CSV is short for Comma-Separated Values, which refers to a tabular data saved as plaintext
where data values are separated by commas. In CSV format:
Each row of the table is stored in one row, i.e., the number of rows in a CSV file are equal to the
number of rows in the table, (or sheet or database table etc.).
The field values of a row are stored together with commas after every field value; but after the last
field’s value, no comma is given, just the end of line.
14. Write a menu-driven program implementing user-defined functions to perform different functions on a
csv file “student” such as:
(a) Write a single record to csv
(b) Write all the records in one single go onto the csv.
(c) Display the contents of the csv file.
Ans. import csv
# To create a CSV File by writing individual lines
def CreateCSV1():
# Open CSV File
Csvfile = open('student.csv', 'w', newline='')
# CSV Object for writing
Csvobj = csv.writer(Csvfile)
while True:
Rno = int(input("Rno:"))
Name = input("Name:")
Marks = float(input("Marks:"))
Line = [Rno, Name, Marks]
# Writing a line in CSV file
Csvobj.writerow(Line)
Ch = input("More(Y/N)?")
if Ch == 'N':
break
Csvfile.close() # Closing a CSV File
# To create a CSV File by writing all lines in one go
def CreateCSV2():
# Open CSV File
Computer Science with Python–XII 4.22 Lines = []
Csvfile = open('student.csv', 'w', newline='')
# CSV Object for writing
Csvobj =csv.writer(Csvfile)
while True:
Rno = int(input("Rno:"))
Name = input("Name:")
Marks = float(input("Marks:"))
Lines.append([Rno, Name, Marks])
Ch = input("More(Y/N)?")
if Ch == 'N':
break