Question:hard

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".

Show Hint

Use csv.reader on States.csv, skip the header with next(), and write rows with int(row[2]) above 10000000 using csv.writer in append mode.
Updated On: Oct 20, 2026
Show Solution

Solution and Explanation

Step 1: List what the program must do.
1. Open the source file and the target file.
2. Ignore the header line.
3. Check the population of every other line.
4. Add the lines that pass to the target file.
5. Close the files.

Step 2: Use the with statement.
With a with block, both files are closed on their own when the block ends. So no close() call is needed.
The target file is opened in 'a' mode, because the records are to be appended.

Step 3: Remove the header.
Read all rows into a list with list(reader). The first item of the list, data[0], is the header.
The slice data[1:] holds only the real records.

Step 4: Compare the population.
The value row[2] is text, such as '52221000'. int(row[2]) turns it into a number, so that it can be compared with 10000000.

Step 5: Write the program.
import csv
with open('States.csv', 'r') as fin, open('More.csv', 'a', newline='') as fout:
    reader = csv.reader(fin)
    writer = csv.writer(fout)
    data = list(reader)
    for row in data[1:]:
        if int(row[2]) > 10000000:
            writer.writerow(row)

Step 6: Test result.
A sample States.csv with Andhra Pradesh (52221000), Sikkim (690000), Goa (1500000) and Bihar (124000000) was used. Only Andhra Pradesh and Bihar were written to More.csv.

Final Answer:
The program writes every state with a population above 10000000 into More.csv, without the header.
Was this answer helpful?
0