繁体   English   中英

如何从 python 中的文本文件中读取数字?

[英]How do I read numbers from a text file in python?

我是 python 的新手,我需要读取文件中的数字并将其加到一个总和中,然后将它们全部打印出来。 格式不是问题,但这些数字不会分别显示在一行上,并且其中一些数字之间有空白行和空格。 如何命令解释器将通常识别为字符串的行视为整数? 这是文件,这是我的代码。

line = eval(infile.read())
    while infile != "":
        sum = sum + int(line)
        count = count + 1
        line = eval(infile.read())
    print("the sum of these numbers is", sum)

数字>>:

111
10 20 30 40 50 60 70
99 98 97
1
2
33
44 55
66 77 88 99 101

123
456

本质上,您需要执行以下操作:

  1. 您需要一个变量,您将在其中存储文件中数字的总和
  2. 您应该使用open以便在with语句中打开文件,我假设您的文件名为file.txt
  3. 您需要逐行迭代文件 object。
  4. 您需要将当前行转换为字符串列表,其中每个元素字符串代表一个数字。 假定文件中的所有元素都是整数,并且它们用空格分隔。
  5. 您需要将该字符串列表转换为整数列表
  6. 您需要对第 5 步列表中的元素求和。并将结果添加到总计中
total = 0 # variable to store total sum

with open('file.txt') as file_object: # open file in a with statement
    for line in file_object:  # iterate line by line
        numbers = [int(e) for e in line.split()] # split line and convert string elements into int
        total += sum(numbers) # store sum of current line

print(f"the sum of these numbers is {total}")
import re

with open(filename, "r")as f:
    l = []
    for line in f:
        l.extend(re.findall(r"\d+", line.strip()))
    print("the sum of these numbers is", sum(map(int, l)))

您可以遍历文件的每一行并将数字添加到我们的total中。

total = 0
with open("input.txt") as file:
    for line in file.readlines():
        total += sum(map(int, line.split()))

print(total)

暂无
暂无

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

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