[Tutor] Performing an union of two files containing keywords
Dave Angel
davea at davea.name
Mon Feb 17 14:16:13 CET 2014
On 02/17/2014 06:12 AM, Oscar Benjamin wrote:
> On 17 February 2014 09:07, Aaron Misquith <aaronmisquith at gmail.com> wrote:
>>
>> 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.
>>
>> 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))
>
> Something like this:
>
> with open(r'D:\file3.txt', 'r+') as fout:
> keywords_seen = set()
> for filename in r'C:\File1.txt', r'C:\File2.txt':
> with open(filename) as fin:
> for line in fin:
> keyword = line.strip()
> if keyword not in keywords_seen:
> fout.write(line)
> keywords.add(keyword)
>
> Why are you opening the output file with mode 'r+'? Are you intending
> to only overwrite part of the file? I think you probably should use
> mode 'w' instead.
>
You forgot to append the newline to strings in the write() method calls.
fout.write(line + "\n")
--
DaveA
More information about the Tutor
mailing list