繁体   English   中英

为什么 python 跳过 txt 文件的第一行

[英]Why is python skipping the first line of a txt file

所以我正在尝试创建一个程序,它从文件中获取数字然后对它们进行平均。 我尝试使用浮点数而不是整数(这是问题想要的),但没有任何效果。 我发现它正在跳过文件的第一行。 txt 文件中的数字是 22、14 和 -99。

#Create main function
def main():

    # Open the file numbers.txt
    numbers = open('numbers.txt', 'r')

    # Initialize an accumulator to 0
    total = 0

    # Initialize a counter
    count = 1

    # Read the values from the file
    number = numbers.readline()

    # Convert the value from string to integer

    for number in numbers:

        value = int(number)

        # Add the new number to the total
        total += value

        # Increase count
        count += 1



    # Close the file
    numbers.close()

    # Average the numbers
    avg = total / count
    # Display the information
    print('The average of the numbers from the file is', avg)
main()

当您执行number = numbers.readline()时,它会从文件中读取第一行。 当您遍历numbers时,它会读取后续行,因此会跳过您已经阅读的行。 如果您想阅读每一行,请摆脱number = numbers.readline()而是for number in numbers.readlines()

尝试这个

def main():
    numbers = open('numbers.txt', 'r')

    lst = [int(number) for number in numbers.read().split("\n")]

    numbers.close()
    avg = sum(lst) / len(lst)
    print('The average of the numbers from the file is', avg)
main()

我发现它正在跳过文件的第一行

我可以看到您的 for 循环在文件 object “数字”上进行迭代,但在此之前 22 由变量number访问(请注意缺少一个 's')。

您也可以通过以下方式获得它。

total = 0
count = 0
with open('numbers.txt', 'r') as f:
    while True:
        line = f.readline()
        if line:
            # Add the new number to the total
            total += int(line)
            # Increase count
            count += 1
        else:
            break


# Average the numbers
print("Total: {}, count: {}".format(total, count))
avg = total // count
# Display the information
print('The average of the numbers from the file is', avg)

考虑使用内置变量__name__来检查脚本是否直接运行。

上下文管理器(即with )和列表理解可以简化您的解决方案。

1 if __name__ == '__main__':
2     with open('numbers.txt', 'r') a fptr:
3         nums = [float(num) for num in fptr.readlines()]
4         avg = sum(nums) / len(nums)
5         print(avg)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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