0

Here is my code, its pretty bad. I am trying to find out if population density was equal, how much population each country would have. The csv file is from wikipedia, having country, population, area, density as columns. It works now, but if I remove the commented blocks, only the first loop will work. The bottom loops will not. The print outside the loop works but not the one inside. I only had 2 loops but added a third to test wtf was happening and yeah, it only works if there's one loop.

import csv

total_population = 0
total_area = 0

with open("C:/Users/Aditya/Desktop/table1.csv", newline="") as csvfile:
    dict1 = csv.DictReader(csvfile)
    dict2 = csv.DictReader(csvfile)

    # for row in dict1:
    #     population = float(row.get("Population"))
    #     area = float(row.get("Area"))
    #     density = population/area
    #     #print(area)
    #     #print(population)
    #     population = float(population)
    #     total_population += population
    #     total_area += area
    average_density = 7910157000/122162000

    def change_population(c_pop, c_den, c_area):
        if c_den < average_density:
            delta_pop = average_density*c_area - c_pop
        elif c_den > average_density:
            delta_pop = c_pop - average_density*c_area
        return delta_pop


    print(f"{total_population} people, {total_area} km2")
    # for row in dict1:
    #     population = float(row.get("Population"))
    #     area = float(row.get("Area"))
    #     density = population/area
    #     print(area)
    #     print(population)
    #     population = float(population)
    #     total_population += population
    #     total_area += area

    for row in dict2:
        population = float(row.get("Population"))
        area = float(row.get("Area"))
        density = float(row.get("Density"))
        change = change_population(population, density, area)
        population2 = str(population + change)
        row.update({"Population": population2})
        print(f"{row}")
rpanai
  • 12,515
  • 2
  • 42
  • 64
p1nk
  • 1
  • 1
  • If you want to go through the file twice, you should `open` the file twice. – rdas Nov 18 '21 at 12:18
  • Have you considered using pandas to manipulate tables? – rpanai Nov 18 '21 at 12:19
  • @rpanai You don't need Pandas for something like this. Pandas has its own bunch of idiosyncracies and added complexity – learning how lists and dicts work first is IMHO paramount. – AKX Nov 18 '21 at 12:20

1 Answers1

1

Once you've looped over a CSV reader, it will have read to the end of the file.

That's why the second for loop appears empty.

You can read all of the lines into memory to begin with with list:

    dict1 = list(csv.DictReader(csvfile))

(In fact, it's not quite safe to use the same file handle for two DictReaders either, since both of them will assume the first line they read is the header line.)

AKX
  • 152,115
  • 15
  • 115
  • 172