Skip to main content
 首页 » 编程设计

python之在 Python 中使用 for 循环读取文件内容

2025年05月04日9kuangbin

问题来了。我有 names.txt 文件。该文件的内容如下。该问题要求显示此文件中的名称数量。我可以使用 while 循环。它有效,没问题。但出于某种原因,如果我想用 for 循环执行此操作,它会给我错误的名称数。

    Julia Roberts  
    Michael Scott 
    Kevin Malone 
    Jim Halpert 
    Pam Halpert 
    Dwight Schrute 

这是 while 循环。它运行完美。

def main(): 
    try: 
        # open the names.txt file in read mode. 
        infile=open("names.txt", "r") 
 
        # set an accumulator for number of names 
        numbers_of_name=0.0 
 
        # read the first line 
        line=infile.readline() 
 
        # read the rest of the file 
        while line!="": 
            numbers_of_name+=1 
            line=infile.readline() 
 
        # print the numbers of names in the names.txt file.     
        print("There are", int(numbers_of_name), "names in the names.txt file.") 
 
        # close the file 
        infile.close() 
    except IOError as err: 
        print (err)  
 
# call the main function 
main() 

控制台给了我正确的答案。

There are 6 names in the names.txt file. 

这是我有问题的 for 循环

def main(): 
    try: 
        # open the names.txt file in read mode. 
        infile=open("names.txt", "r") 
 
        # set an accumulator for number of names 
        numbers_of_name=0.0 
 
        # read the rest of the file 
        for line in infile: 
            line=infile.readline() 
            numbers_of_name+=1 
 
        # print the numbers of names in the names.txt file.     
        print("There are ", numbers_of_name, "names in the names.txt file.") 
 
        # close the file 
        infile.close() 
    except IOError as err: 
        print (err)  
 
# call the main function 
main() 

这是输出。

There are  3.0 names in the names.txt file.  

应该有 6 个名字而不是 3 个名字。:

此文件读取代码中可能缺少什么部分?提前致谢。

请您参考如下方法:

问题是你在每次迭代中读取两行,当你这样做时:

for line in infile: 

行是文件中的第一行,当你这样做时:

line.readline() 

然后一行现在是第二行,然后你加一二你的名字计数

你应该这样做:

for line in infile: 
    numbers_of_name+=1