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

标签 python for-loop while-loop

问题来了。我有 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

关于python - 在 Python 中使用 for 循环读取文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54068537/

相关文章:

python - TypeError : getsockaddrarg: AF_INET address must be tuple,未列出

python - 如果模式匹配,则在 Pandas 的列值中添加子字符串

Javascript 自定义函数,在 for 循环内进行检查

Java Math.random 在 while 循环中不是随机的

javascript - 使用 While Loop 和 Momentjs 构建一个以年为单位递增月份的函数

javascript - 在哪些情况下我应该使用 'while loops' 而不是 JavaScript 中的“for 循环”?

python re.X vs automagic 行延续

python - 每个 Flask session 存储大数据或服务连接

arrays - for 循环中的协议(protocol)一致性检查?

php - MySQL 内部 for 循环。插入仅在第一个循环上运行