Write a program that reads two country data files, worldpop.txt
and worldarea.txt
. Both files contain the same countries in the same order. Write a file density.txt
that contains country names and population densities (people per square km).
worldpop.txt:
China 1415045928
India 1354051854
U.S. 326766748
Indonesia 266794980
Brazil 210867954
Pakistan 200813818
Nigeria 195875237
Bangladesh 166368149
Russia 143964709
Mexico 130759074
Japan 127185332
Ethiopia 107534882
Philippines 106512074
Egypt 99375741
Viet-Nam 96491146
DR-Congo 84004989
Germany 82293457
Iran 82011735
Turkey 81916871
Thailand 69183173
U.K. 66573504
France 65233271
Italy 59290969
worldarea.txt:
China 9388211
India 2973190
U.S. 9147420
Indonesia 1811570
Brazil 8358140
Pakistan 770880
Nigeria 910770
Bangladesh 130170
Russia 16376870
Mexico 1943950
Japan 364555
Ethiopia 1000000
Philippines 298170
Egypt 995450
Viet-Nam 310070
DR-Congo 2267050
Germany 348560
Iran 1628550
Turkey 769630
Thailand 510890
U.K. 241930
France 547557
Italy 294140
density.txt should be like this:
China 150.7258334947947
India 455.42055973550293
U.S. 35.72228540943785
Indonesia 147.27279652456156
Brazil 25.22905263611282
Pakistan 260.49945257368205
Nigeria 215.06553465748763
Bangladesh 1278.0836521471922
Russia 8.790734065789128
Mexico 67.26462820545795
Japan 348.8783091714556
Ethiopia 107.534882
Philippines 357.2192843009022
Egypt 99.8299673514491
Viet-Nam 311.1914922436869
DR-Congo 37.054757945347475
Germany 236.0955273123709
Iran 50.35874550980934
Turkey 106.43669165703
Thailand 135.41696451290883
U.K. 275.1767205389989
France 119.13512383185677
Italy 201.57397497790168
Program I write:
f=open('worldpop.txt','r')
f2=open('worldarea.txt','r')
out=open('density.txt','w')
for line1 in f: #finding country names
pos1=line1.find(' ')
country=line1[0:pos1]+'\n'
for line2 in f: #finding population numbers
pos2=line2.find(' ')
population=line2[pos2+1:]
for line3 in f2: #finding area numbers
pos3=line3.find(' ')
area=line3[pos3+1:]
for line1 in f: #writing density to a new file
density=population/area
out.write(density)
out.close()
f.close()
f2.close()
When I run the program, density.txt is empty. How can I fix this problem? Thanks. Note: I know the alternative solutions of it, but I mainly want to use this method to solve it, so please do not use other methods.