[英]Ordered file combination with python
I have two files, file1
and file2
, with each one containing several numbers (one number per line). 我有两个文件
file1
和file2
,每个文件包含多个数字(每行一个数字)。 I need to create a third file ( output file
) that combines both files without having any repeated number. 我需要创建第三个文件(
output file
),该文件将两个文件合并在一起而没有任何重复编号。 What should be the code for combining both files in a file? 将两个文件合并到一个文件中的代码应该是什么?
File1: 1 2 7 9 15 (1 number per line)
File2: 1 8 12 13 14 16 (1 number per line)
Outputfile: 1 2 7 8 9 12 13 14 15 16 (1 number per line)
Assuming your input files are in the current working directory: 假设您的输入文件位于当前工作目录中:
unique_elements = set()
for filename in ['file1', 'file2']:
with open(filename, 'r') as f:
for l in f.readlines():
unique_elements.add(int(l.strip()))
sorted_list = list(unique_elements)
sorted_list.sort()
with open('output_file', 'w') as f:
for number in sorted_list:
f.write('{}\n'.format(number))
So if order matters, you could simply read both into a list and then write a final one, similar to: 因此,如果顺序很重要,您可以将它们都读入一个列表,然后写一个最终的列表,类似于:
numbers = []
with open(file1, 'r') as inputfile:
for row in inputfile.readlines():
number = int(row)
if number not in numbers:
numbers.append(number)
with open(file2, 'r') as inputfile:
for row in inputfile.readlines():
number = int(row)
if number not in numbers:
numbers.append(number)
numbers.sort()
with open(file3, 'w') as outputfile:
for number in numbers:
outputfile.write("%d\n" % number)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.