2

I am trying to separate my wordlist for a school project, the list is Country:Population

China:1382323332
India:1326801576
USA:324118787
Indonesia:260581100

and so on...

i have done this code Warning its messy and there are some duplicates:

Data = open("CountryList.txt","r")
DATA = Data.readlines()
file = "CountryList.txt"
Test = open(file,'r')
for x in range(0,len(DATA)):
   for lines in Test.readlines():
       Country,Population = lines.split(':')
print(Country)
print(Population)

the result is:

Egypt
93383574
Egypt
93383574
Egypt
93383574

for 13x more

I want this to put the Country in a Country list and the Population in a Population List so the result would be

USA 
324118787
China
1382323332

How can I achieve this?

3 Answers 3

3

You need the print statements to be in the for loop body. Also you're doing too much. Please see condensed code.

with open("CountryList.txt","r") as fin:
    for line in fin:
        Country,Population = line.split(':')
        print(Country)
        print(Population)

As you can see from the above: you can iterate directly over the file without using .readlines().

Also note that the with statement closes the file automatically so you don't need fin.close()

Sign up to request clarification or add additional context in comments.

Comments

1

Indent your two print calls so that they are inside your innermost loop(s), at the same level of nesting as the lines on which they are assigned. Currently you let the innermost loop run to the end, assigning and re-assigning Country and Population over and over, but and only at the end do you print their values.

Then, set about pruning your loop structure. You only need one loop, not two nested ones. You only need to open the file once and read its data once.

Comments

0

As it could be seen that you are looping over the same values again and again and for reading data from a single you don't need nested loops, one loop should be enough to get what you actually want, perhaps like this,

country = []
population = []
with open("lolla.txt", 'r') as fp:
    for line in fp.readlines():
        c, p = line.split(':')
        country.append(c)
        population.append(p)

print country
print population

print zip(country, population)

and in your code Country, Population are just two variables and no matter how many times your for loop might iterate they will end up storing only the last initialized values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.