Test Index
CBSE Class 12 Computer Science 2026 Paper Set 4
© examsnet.com
Question : 33 of 37
Marks:
+1,
-0
A csv file "States.csv" contains some data about all the states of India. Each record of the file contains the following data :• Name of the State• Capital of the State• Population of the State• Official Language of the StateFor example, a sample record in the file is :
['Andhra Pradesh','Amaravati',52221000,'Telugu']Write a Python program which reads the data from this file and appends all those records where population is more than 10000000 into another csv file 'More.csv'.Note : "States.csv" also contains the Header row. The Header row should NOT be copied to "More.csv".
Solution:
Concept: The
csv module gives csv.reader (each row comes as a list of strings) and csv.writer (writerow() writes one list as a row). “Append” means opening More.csv in mode 'a'. next(reader) reads and discards the header row.import csvF1 = open("States.csv", "r", newline='')F2 = open("More.csv", "a", newline='')reader = csv.reader(F1)writer = csv.writer(F2)next(reader) # skip the header rowfor rec in reader: if int(rec[2]) > 10000000: # population is the 3rd field writer.writerow(rec)F1.close()F2.close()Explanation:• Every field read from a csv file is a string, so the population rec[2] is converted with int() before comparing.• The sample record has population 52221000 > 10000000, so it is written to More.csv; a state with a smaller population is skipped.• newline='' stops blank lines between rows on Windows.© examsnet.com
Go to Question: