如何逐行读取文件

-1 投票
3 回答
53 浏览
提问于 2025-04-13 19:53

我有一个文本文件,我想打开它。打开后,我想读取并打印出文件中的每一行。我的问题是,我的代码只读取了每隔一行的内容。例如,如果我的文本文件里有这些内容:

bob
cat
dog
bacon

那么它只会读取并打印出:

bob
dog

而跳过了另外两行。

def main8():
    count = 1
    askName = input('Whats the name of the file your trying to see? ')
    infile = open(askName,'r')
    for row in infile:
        line = infile.readline()
        line = line.rstrip('\n')
        print(count,':', line, sep='\t')
        count += 1
    infile.close
main8()

3 个回答

1

如果你想要一个循环来手动读取文件中的每一行,可以使用一个无限循环,并在每次调用readline时检查返回的内容是否为空字符串。

while True:
    line = infile.readline()
    if line == '':
        break
    line = line.rstrip('\n')
    print(count,':', line, sep='\t')
    count += 1

文件类对象实现的迭代器协议会自动为你调用readline

for line in infile:
    line = line.rstrip('\n')
    print(count,':', line, sep='\t')
    count += 1

你还应该使用with语句,这样可以确保文件在使用完后被正确关闭。同时,你可以使用enumerate来自动生成行号。

def main8():
    askName = input('Whats the name of the file your trying to see? ')
    with open(askName,'r') as infile:
        for count, line in enumerate(infile, start=1):
            line = line.rstrip('\n')
            print(count,':', line, sep='\t')

main8()
2

你代码的问题在于,你用for循环来逐行读取文件的同时,又在循环里使用了readline()。当你用for循环读取文件的每一行时,其实已经在一个一个地读取了。如果在循环里再用readline(),就会导致每隔一行就跳过,因为它会把文件指针移动到下一行。

要解决这个问题,你只需要把循环里的readline()那一行去掉就可以了。下面是修正后的代码:

def main8():
    count = 1
    askName = input('What\'s the name of the file you\'re trying to read? ')
    with open(askName, 'r') as infile:  # Using "with" ensures the file is properly closed
        for line in infile:  # Iterating directly over the lines of the file
            line = line.rstrip('\n')
            print(count, ':', line, sep='\t')
            count += 1

main8()
2

好的,for row in infile 这个语句是用来逐行读取文件的内容。接着,infile.readline() 是用来读取下一行的。不过你并没有用到 row 这个变量,所以你实际上是在丢掉每隔一行的内容。

你可以把循环中的变量改成 line,然后去掉 line = infile.readline() 这一行,这样就可以正常工作了。

for line in infile:
    line = line.rstrip('\n')
    ...

撰写回答