如何读取文件中的每一行

问题描述 投票:0回答:1

所以我有一个正在打开的txt文件。当我打开它时,我想读取并打印该文件中的每一行。我的问题是我的代码只读取每隔一行。对于前。如果我的 txt 文件包含以下单词

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()
python file
1个回答
0
投票

嗯,

for row in infile
迭代文件的行。然后,
infile.readline()
读取下一行。您没有使用
row
,因此您将丢弃所有其他行。

© www.soinside.com 2019 - 2024. All rights reserved.