हिंदी

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 - Computer Science (Python)

Advertisements
Advertisements

प्रश्न

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".
कोड लेखन
Advertisements

उत्तर

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
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
2025-2026 (March) Set 4
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×