python - 将两个文件中的数字相加(逐行)

标签 python python-3.x python-2.7

我有两个文件,都有大约 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/

相关文章:

python - 在 Python 3 中抑制 "Exception ... ignored"消息的打印输出

Python 和 openpyxl 正在将我的共享工作簿保存为非共享

python - sqlalchemy 插入数据不起作用

python - Python 中的产量

python - Python列表中的索引包含多个元素。如何访问每个并将它们传递给不同的函数?

django - 我是否需要将 __init__.py 放在通向我的类(class)的目录树中的每个目录中?

python - Django 无法看到我添加到表和模型中的新列

python - 如何从 Python 中的文件名列表中删除文件名的扩展名?

python - AWS Lambda 调用 url 花费的时间超过 Lambda 执行限制

python-2.7 - urllib3.HTTPSConnectionPool 错误