Advertisements
Advertisements
Question
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 State
For 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".Code Writing
Advertisements
Solution
import csv
# Use 'States.csv' as per the question
f1 = open('States.csv', 'r', newline='')
reader = csv.reader(f1)
# IMPORTANT: Skip the header row so it's not copied
next(reader)
records = []
for rec in reader:
# Check if population (index 2) is > 10,000,000
if int(rec[2]) > 10000000:
records.append(rec)
f1.close()
# Use 'a' mode because the question asks to "append"
f2 = open('More.csv', 'a', newline='')
writer = csv.writer(f2)
writer.writerows(records)
f2.close()shaalaa.com
Is there an error in this question or solution?
