我无法让我的程序垂直打印我的文本文件

时间:2018-01-06 09:36:53

标签: python

我制作了一个文本文件:

52 57 63 69 71 78 82 84 95 96

我需要用相应的数字垂直打印,包括所有数字的总和,但我只想出这个:

with open("numbers.txt", "r") as f:
    a = [int(n) for line in f.readlines() for n in line.split()]
    print a
    print("\n")

with open("numbers.txt", "r") as f:
    for l in f:
        print(sum([int(a) for a in l.split()]))

4 个答案:

答案 0 :(得分:0)

你很亲密。试试这个:

with open('numbers.txt', 'r') as fl:
    text = fl.read()

numbers = [int(n) for n in text.split()]

answer = sum(numbers)

for n in numbers:
    print(n)
print(answer)

这会产生:

52
57
63
69
71
78
82
84
95
96
747

答案 1 :(得分:0)

您不需要两次读取文件

with open("numbers.txt", "r") as f:
  for line in f:
    a = line().split()
    for x in a
        print(x)
    print(sum(int(x) for x in a))

答案 2 :(得分:0)

代码中的一些更改:

with open("numbers.txt", "r") as f:
    a = [int(n) for line in f.readlines() for n in line.split()]
    for i in a:
        print(i)
    print("Sum: ", sum(a))

输出:

69
71
78
82
84
95
96
Sum:  747

答案 3 :(得分:0)

如果文本文件只有一行,您可以使用f.readline()阅读,如下所示:

with open('test.txt') as f:
    nums = [int(n) for n in f.readline().split()]

for num in nums:
    print(num)

print()
print(sum(nums))

52
57
63
69
71
78
82
84
95
96

747
>>>