简体   繁体   中英

Ordered file combination with python

I have two files, file1 and file2 , with each one containing several numbers (one number per line). I need to create a third file ( output file ) that combines both files without having any repeated number. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM