简体   繁体   中英

Reading a text file into list in python

I'm trying to learn python. This is a little test program that I made to read a text file into a list. This is the text file:

42 1
35 5
50 2
41 6
42 3
48 4

And this is my codes:

score = [];

for i in range(0, 51):
    score.append(0);

f = open("test1.txt", "r");

for line in f:
    a, b = map(int, f.readline().split());
    score[a] = score[a] + b;

print(score);

I'm trying to imitate the array in C++ with list. Read in each line from the text file, first number of the line is the position in the list that will hold the value of the second number. For some reason the program is skipping the 1st, 3rd, 5th lines. This is the result when I run the program.

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 4, 0, 0]

It was supposed to be

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 6, 4, 0, 0, 0, 0, 0, 4, 0, 2]

Any idea where I might have done wrong? This is Python 3

When you write for line in f: , that loops over the file, reading one line at a time.

Then, inside that loop, you ignore line and instead do f.readline() , which reads the next line.

So, you read line 0, ignore it, read line 1, and process it. Then read line 2, ignore it, read line 3, and process it. And so on.

Just use line instead of f.readline() and everything will be fine.

The readline() call is the problem. You are iterating through each line with for line in f , but each time through the loop, you read an extra line with readline() so it is only reading every other line.

在python中,如果要使用for循环遍历每个文件,则可以使用迭代值:

a, b = map(int, line.split());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM