Как вывести сумму чисел в выходной файл - PullRequest
0 голосов
/ 11 апреля 2019

Итак, я должен создать код, который читает мой входной файл с именем «numbers.txt», который состоит из цифр 1-10, но как мне заставить код записать сумму в выходной файл ?. Мой код уже сообщает мне общую сумму, но как мне сделать так, чтобы в моем выходном файле "outputnumbers.txt" были цифры 1-10 плюс сумма?

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))

print('Total of all numbers: {}'.format(total))

1 Ответ

1 голос
/ 11 апреля 2019

Попробуйте следующее.
Я только что добавил строку outp.write('\n'+str(total)), чтобы добавить сумму чисел после того, как цикл for завершит вычисление суммы

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
...