I have a problem adding string from a .txt file to a list, even after trying to use .append

Viewed 28

The program reads in a line like "Joe:100" and it splits it in the middle, it's then supposed to place the name into one list and the number it another.

Here is what I have:

def splitData(num,person):
counter = 0
with open ("Data.txt") as file_object:

    for line in file_object:
        line = file_object.readline()
        words = line.split(":")

        num.append(words[1])
        person.append(words[0])

I feel like I'm close to getting it right but then again I could be miles off.

1 Answers
for line in file_object:
    line = file_object.readline()

These 2 lines both read a line, so every iteration you are skipping a line.

for line in file_object: is all you need to read a file line by line.

You will also probably want to do line.strip() to remove the newline character at the end of your numbers

Related