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()
Python: How do I calculate the sum of numbers from a file?
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.
How to sum numbers from a text file in Python
I have a code that relies on me reading a text file, printing off the
numbers where there are numbers, printing off specific error messages
where there are strings instead of numbers, then summing ALL the
numbers up and printing their sum (then saving ONLY the numbers to a
new text file).
So you have to do the following:
- Print numbers
- Print a message when there isn't a number
- Sum the numbers and print the sum
- Save only the numbers to a new file
Here is one approach:
total = 0
with open('input.txt', 'r') as inp, open('output.txt', 'w') as outp:
for line in inp:
try:
num = float(line)
total += num
outp.write(line)
except ValueError:
print('{} is not a number!'.format(line))
print('Total of all numbers: {}'.format(total))
Python : Sum of numbers in different files
Assuming you know the file format beforehand and have a list of file names, you just iterate over the files and accumulate the sums in a list of lists of the right size:
nrows, ncols = 2, 5 # 800, 800 in your real code
sums = [[0] * ncols for _ in range(nrows)]
file_names = ["file1.txt", "file2.txt"]
for file_name in file_names:
with open(file_name) as f:
for i, row in enumerate(f):
for j, col in enumerate(row.split()):
sums[i][j] += int(col)
for row in sums:
print(*row)
# 29 88 81 55 43
# 65 64 34 70 99
Alternatively using numpy.loadtxt
:
import numpy as np
sum(np.loadtxt(file_name, dtype=int) for file_name in file_names)
# array([[ 29, 88, 81, 55, 43],
# [ 65, 64, 34, 70, 99]])
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
How do I print the sum of the numbers into the output file
Try the following.
I just added a line outp.write('\n'+str(total))
to add the sum of numbers after the for loop finishes calculating the sum
total = 0
with open('numbers.txt', 'r') as inp, open('outputnumbers.txt', 'w') as outp:
for line in inp:
try:
num = float(line)
total += num
outp.write(line)
except ValueError:
print('{} is not a number!'.format(line))
outp.write('\n'+str(total))
print('Total of all numbers: {}'.format(total))
numbers.txt
1
2
3
4
5
6
7
8
9
10
outputnumbers.txt
1
2
3
4
5
6
7
8
9
10
55.0
Related Topics
Python: How to Keep Repeating a Program Until a Specific Input Is Obtained
How to Call a Classes Method from Another Class Without Initialising the First Class
Python - Outputting Variables to Txt File
Hiding Raw_Input() Password Input
Discord.Py Show Who Invited a User
Matplotlib: Attributeerror: 'Axessubplot' Object Has No Attribute 'Add_Axes'
Python Opencv Cv2 - How to Increase the Brightness and Contrast of an Image by 100%
How to Merge Json Objects Containing Arrays Using Python
Concatenate Two Columns in Csv: Python
How to Remove a Pandas Dataframe from Another Dataframe
Replace Empty Strings With None/Null Values in Dataframe
What Is the Correct Way to Make My Pyqt Application Quit When Killed from the Console (Ctrl-C)
Convert String to Python Class Object
How to Create Dynamic Workflows in Airflow