我有两个仅包含数字的txt文件(每行数),所以我想将第1行和第1行连续添加到每个文件的最后一行。每个文件都有相同的行号。
我正在尝试这种方式,但我只能打印第一行
arq = open ("List1.txt")
arq2 = open ("List2.txt")
x = [linha.strip() for linha in arq]
arq.close()
y = [linha.strip() for linha in arq2]
arq2.close()
for linha in x:
index = 0
while index<len(x):
result = (int(x[index]) + int(y[index]))
index += 1
print result
答案 0 :(得分:1)
您可以使用zip
轻松实现此目标。
将相关代码行更改为:
for x, y in zip(arq, arq2):
result = int(x) + int(y)
print(result)
答案 1 :(得分:1)
虽然您应该使用上面提到的zip
,但如果您想继续使用您的做事方式,那么您的问题就在这里
当你在python中循环for
时,它是一个foreach,所以当你这样做时
for linha in x:
print linha
linha
将是x[n]
的值,其中n是循环的迭代
无论如何,修复你要做的代码
# no need for the for loop, pull everything back
index = 0
while index< min(len(x), len(y)): # make sure you check for both lengths in case they are not the same
result = (int(x[index]) + int(y[index]))
index += 1
print result # you want to print the result inside the loop so you don't lose it on the next iteration
这样做的正确方法是
for n,p in zip(x,y):
print int(n) + int(p)
答案 2 :(得分:0)
首先,我会得到一个numpy数组并连接
import numpy as np
file1 = np.genfromtxt('file1')
file2 = np.genfromtxt('file2')
file3 = np.concatenate((file1, file2), axis=1)
然后保存你认为合适的