[Tutor] Performing an union of two files containing keywords

Peter Otten __peter__ at web.de
Mon Feb 17 10:46:15 CET 2014


Aaron Misquith wrote:

> I have 2 different text files.
> 
> File1.txt contains:
> 
> file
> RAMPython
> parser
> 
> File2.txt contains:
> 
> file1234
> program
> 
> I want to perform an union of these both files such that i get an output
> file3.txt which contains:
> 
> file
> RAMPython
> parser1234
> program
> 
> 
> 
> The program that i'm working on just combines two files. Any help on
> performing an union such that a keyword would not be repeated would be
> appreciated.

Have a look at the set class and its update() method.
 
> Code:
> with open("C:\\File1.txt") as fin1: lines = fin1.readlines()
> with open("C:\\File2.txt") as fin2: lines.extend(fin2.readlines())
> with open("D:\\file3.txt", "r+") as fout: fout.write('\n'.join(lines))

fout.write("\n".join(lines))

will add extra newlines to the already existing ones.

Use 

fout.writelines(lines)

instead.



More information about the Tutor mailing list