为什么看起来只有最后一行在文本文件中被读取?

Why does it seem like only the last line is being read in the text file?

我对此很陌生,所以请原谅任何新手错误。

所以我的代码的目标是使用文本文件 ("Numbers.txt") 中的 3 行数据逐行执行一些计算。然后我想将这些计算的结果写入一个新的文本文件(“Newnumbers.txt”)。

“Numbers.txt”文件包含以下 3 行数据:

1, 2, 3, 4, 5, 6, 7
2, 4, 6, 8, 10, 12, 14
1, 3, 5, 7, 9, 11, 13

每当我 运行 这段代码时,似乎只有最后一行被读取。 “计算结果”打印为 [2, 4, 14, 2, 4, 14, 2, 4, 14].

我哪里错了?我非常感谢任何帮助:)

这是我的脚本:

numbers = open("Numbers.txt", "r")

for line in numbers:
    (m, a, e, i, o, O, E) = line.split(",")
    print(line)
    m = int(m)
    a = int(a)
    e = int(e)
    i = int(i)
    o = int(o)
    O = int(O)
    E = int(E)

numbers.close()

x = 0
y = 0
z = 0

calcresults = []

numbers = open("Numbers.txt", "r")

for line in numbers:
    x = m*2
    y = m+a
    z = m+E
    calcresults.append(x)
    calcresults.append(y)
    calcresults.append(z)

print(calcresults)

calcresults = str(calcresults)

newnumbers = open("Newnumbers.txt", "w")
newnumbers.write(calcresults)

numbers.close()
newnumbers.close()`
for line in numbers:
    (m, a, e, i, o, O, E) = line.split(",")
    print(line)
    m = int(m)
    a = int(a)
    e = int(e)
    i = int(i)
    o = int(o)
    O = int(O)
    E = int(E)

每次执行此循环时,您都会丢弃 m、a、e 等的先前值

这就是你想要的:

numbers = open("Numbers.txt", "r")

calcresults = []

for line in numbers:
    (m, a, e, i, o, O, E) = line.split(",")
    print(line)
    m = int(m)
    a = int(a)
    e = int(e)
    i = int(i)
    o = int(o)
    O = int(O)
    E = int(E)
    x = m*2
    y = m+a
    z = m+E
    calcresults.append(x)
    calcresults.append(y)
    calcresults.append(z)

print(calcresults)

calcresults = str(calcresults)