我有两个文件,都有大约 10 行随机数。我想将 file1 中的每一行添加到 file2 中的相应行。我可以在每个文件中只使用一个数字来完成此操作,但有多行数字都在挣扎。例如 这是我尝试过的:
file1 = open("file1.txt").read()
file2 = open("file2.txt").read()
result = int(file1) + int(file2)
print(result)
最佳答案
第一步是从文件(程序失败的地方)正确获取数字,然后将它们添加到新列表中。为了制作一个更健壮的程序,我们将捕获一个简单的边缘情况(当两个列表没有相同数量的参数时),作为奖励,您不必对每个文件中的行数进行硬编码:
from itertools import zip_longest
try:
with open("file1") as file1, open("file2") as file2:
numbers1 = [int(line) for line in file1.readlines()]
numbers2 = [int(line) for line in file2.readlines()]
result = [line[0] + line[1] for line in zip_longest(numbers1, numbers2, fillvalue=0)]
except FileNotFoundError:
print("Error opening files")
示例测试:
文件1:
7
1
5
9
7
9
10
3
10
8
文件2:
9
9
8
2
8
5
2
8
9
>>> result
[16, 10, 13, 11, 15, 14, 12, 11, 19, 8]
您必须注意到文件的行数不同,file1(10)、file2(9),我用这个例子来显示您的情况的不确定程度:
both have about 10 lines of random numbers
关于python - 将两个文件中的数字相加(逐行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60944096/