简体   繁体   English

Python:如何计算文件中的数字总和?

[英]Python: How do I calculate the sum of numbers from a file?

How do I calculate the sum of numbers from a .txt file? 如何计算.txt文件中的数字总和?

Data in file is formatted as: 文件中的数据格式为:

7
8
14
18
16
8
23
...

I read the data from the file and assign every line value to 'line' vatiable, but I want to get something like: result = 7+8+14+... 我从文件中读取数据并将每个行值分配给'line'可变,但我希望得到类似的result = 7+8+14+...result = 7+8+14+...

f = open('data.txt', 'r')   #LOOP AND READ DATA FROM THE FILE
    for line in f:
        code

This is most compact code I can think of right now: (updated to handle the n at the end, thanks, @JonClements!) 这是我现在能想到的最紧凑的代码:(更新到最后处理n ,谢谢@JonClements!)

with open('file.txt', 'r') as fin:
    ans = sum(int(line) for line in fin if line.strip().isnumeric())

For the code structure you have, you can also go for this: 对于您拥有的代码结构,您也可以这样做:

f = open('data.txt', 'r')
ans = 0
for line in f:
    try:
        ans += int(line.strip())
    except ValueError:
        pass

Edit: Since the confusion with the 'n' has been cleared, the first example can be as simple as 编辑:由于与'n'的混淆已被清除,第一个例子可以很简单

with open('file.txt', 'r') as fin:
    ans = sum(int(line) for line in fin)

Or even this one-liner: 甚至这个单线:

ans = sum(int(line) for line in open('file.txt', 'r'))

But there are certain risks with file handling, so not strongly recommended. 但文件处理存在一定的风险,因此不强烈建议。

file = open("data.txt", "r")
numbers = []

for line in file:
  numbers.append(int(line))

print(sum(numbers))

This basically just creates a list of numbers, where each line is a new entry in the list. 这基本上只创建一个数字列表,其中每一行都是列表中的新条目。 Then it shows the sum of the list. 然后它显示列表的总和。

A simple solution is, it will take care of the \\n at the end of each line as well, based on steven's and AChamp's suggestion 一个简单的解决方案是,它将根据史蒂文和AChamp的建议,在每一行的末尾处理\\ n

with open("abc.txt","r")as f:
    print(sum(int(x) for x in f))

Keep it simple: 把事情简单化:

with open('data.txt', 'r') as f:
    result = sum(map(int, f))

int is mapped over each line from f , then sum() adds up the resulting integers. intf映射到每一行,然后sum()将得到的整数相加。

Here is a solution (consider all of the lines are numbers): 这是一个解决方案(考虑所有行都是数字):

def calculate_number_in_file(file_path):
    with open(file_path, 'r') as f:
        return sum([int(number.strip()) for number in f.readlines()])

On smartphone... 在智能手机......

with open(filepath) as f:
    lines = f.readlines()
numbers = [int(line) for line in lines]
print(sum(numbers))
with open ('data.txt', 'r') as f:
    data = f.readlines()

sum = 0
for line in data:
    sum += int(line.strip())

print(sum)

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

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