目前,您在读取每个输入文件的内容后立即将其写入输出 (outfile.write(infile.read() + "\n"))。要处理它们,我建议您先将它们读入列表,然后从那里开始工作。
要从每个文件创建整数列表,有多种方法。一种是用.read() 将整个文件读入一个字符串,用.strip() 去除多余的空格和换行符,然后在换行符处拆分。然后,您可以使用列表推导式或映射或一些等效方法将此数字字符串列表转换为整数列表。
然后你需要将这两个列表组合起来并排序。有很多算法可以解决这个问题。由于您的任务没有指定,您可以使用内置的sorted() 函数或列表方法.sort()。这将必须对由两个列表连接在一起的列表进行操作。要在 Python 中连接两个列表,我们只需添加它们 ([1, 2] + [3, 4] == [1, 2, 3, 4])。
因此,您的最终解决方案可能类似于:
filenames = ['numbers1.txt', 'numbers2.txt']
num_lists = [[int(x) for x in open(f).read().strip().split('\n')] \
for f in filenames]
with open('all_numbers.txt', 'w') as outfile:
outfile.write('\n'.join(str(x) for x in sorted(sum(num_lists, []))) + '\n')
print('Your file is saved under all_numbers.txt')
请注意,sum(numbers_list, []) 等同于 numbers_list[0] + numbers_list[1],但更好,因为您的解决方案现在适用于任意数量的输入文件。 :)
测试
$ echo '20
> 10
> 30
> 50
> 40
> 60' > numbers1.txt
$ echo '999
> 80
> 150
> 101
> 100' > numbers2.txt
$ python -q
>>> filenames = ['numbers1.txt', 'numbers2.txt']
>>> num_lists = [[int(x) for x in open(f).read().strip().split('\n')] \
... for f in filenames]
>>> with open('all_numbers.txt', 'w') as outfile:
... outfile.write('\n'.join(str(x) for x in sorted(sum(num_lists, []))) + '\n')
...
37
>>> print('Your file is saved under all_numbers.txt')
Your file is saved under all_numbers.txt
>>>
$ cat all_numbers.txt
10
20
30
40
50
60
80
100
101
150
999