How to Quickly Sum All Numbers in a File

How can I quickly sum all numbers in a file?

For a Perl one-liner, it's basically the same thing as the awk solution in Ayman Hourieh's answer:

 % perl -nle '$sum += $_ } END { print $sum'

If you're curious what Perl one-liners do, you can deparse them:

 %  perl -MO=Deparse -nle '$sum += $_ } END { print $sum'

The result is a more verbose version of the program, in a form that no one would ever write on their own:

BEGIN { $/ = "\n"; $\ = "\n"; }
LINE: while (defined($_ = <ARGV>)) {
chomp $_;
$sum += $_;
}
sub END {
print $sum;
}
-e syntax OK

Just for giggles, I tried this with a file containing 1,000,000 numbers (in the range 0 - 9,999). On my Mac Pro, it returns virtually instantaneously. That's too bad, because I was hoping using mmap would be really fast, but it's just the same time:

use 5.010;
use File::Map qw(map_file);

map_file my $map, $ARGV[0];

$sum += $1 while $map =~ m/(\d+)/g;

say $sum;

How to calculate the sum of numbers in one file and print the result into another file in Python?

The lines you're reading from the input file are strings so you need to convert them to ints. Also, each line will have a newline character '\n' at the end which will need to be removed before you can successfully convert each line to an int.

There are also several other issues with your code example. Sum is a list, but aren't you trying to add each int from input.txt? Also if i.isdigit() is not indented. try, except can be used instead though.

x = open("input.txt", "r")
Sum = 0
z = x.readlines()
for i in z:
try:
Sum += int(i.strip())
except ValueError:
pass

x.close()
y= open ("output.txt", "w")
y.write(str(Sum))
y.close()

How can I sum integers from multiple text files into a new text file using python?

I'd use generators so you don't have to load all of the files into memory at once (in case they're large)

Then just pull the next value from each generator, sum them, write them and carry on. When you hit the end of the file you'll get a StopIteration exception and be done

def read_file(file):
with open(file, "r") as inFile:
for row in inFile:
yield row

file_list = ["file1.txt", "file2.txt", ..., "file10.txt"]
file_generators = [read_file(path) for path in file_list]

with open("totals.txt", "w+") as outFile:
while True
try:
outFile.write(f"{sum([int(next(gen)) for gen in file_generators])}\n")
except StopIteration:
break


Related Topics



Leave a reply



Submit