2017-05-09 57 views
1

我有兩個文本文件,名字是one.txt,同時two.txt 在此時就把one.txt存盤,內容是如何比較和合並在Python兩個文件

AAA 
BBB 
CCC 
DDD 

在two.txt,內容是

DDD 
EEE 

我希望有一個Python代碼,以確定包含two.txt都出現在此時就把one.txt存盤或不 如果存在的話手段,不要做任何事情,但如果two.txt內容不存在手段,它應該附加到one.txt

我想在此時就把one.txt存盤一個輸出

AAA 
BBB 
CCC 
DDD 
EEE 

代碼:

file1 = open("file1.txt", "r") 
file2 = open("file2.txt", "r") 
file3 = open("resultss.txt", "w") 
list1 = file1.readlines() 
list2 = file2.readlines() 
file3.write("here: \n") 
for i in list1: for j in list2: 
    if i==j: file3.write(i) 
+0

請直接在問題中編輯您的代碼。 – timgeb

+0

請將代碼添加到您的問題並縮進四個空格以保留格式;註釋並不適用於此,特別是對於像Python這樣的空白相關語言:) –

+0

生成的文件是否需要特定的順序?在你的例子中,你的兩個源文件被排序 - 是假定的嗎?可能所有三個文件同時在內存中(所以文件不是很大)? –

回答

4

是與sets簡單,因爲它照顧了重複的爲你

編輯

with open('file1.txt',"a+") as file1, open('file2.txt') as file2: 
    new_words = set(file2) - set(file1) 
    if new_words: 
     file1.write('\n') #just in case, we don't want to mix to words together 
     for w in new_words: 
      file1.write(w) 

編輯2

如果順序很重要,請與Max Chretien答覆。

如果你想知道的常用詞,你可以使用交集

with open('file1.txt',"a+") as file1, open('file2.txt') as file2: 
    words1 = set(file1) 
    words2 = set(file2) 
    new_words = words2 - words1 
    common = words1.intersection(words2) 
    if new_words: 
     file1.write('\n') 
     for w in new_words: 
      file1.write(w) 
    if common: 
     print 'the commons words are' 
     print common 
    else: 
     print 'there are no common words' 
+1

'set(file1)|設置(文件2)'? – stamaimer

+0

其實我想在file1.txt本身的結果,不需要輸出文件@Copperfield –

+0

@stamaimer工作太多,但我認爲,更新不會創建中間扔扔集 – Copperfield

1

這應做到:

with open('file1.txt', 'r+') as file1, open('file2.txt') as file2: 
    f1 = [i.strip() for i in file1.readlines()] 
    f2 = [j.strip() for j in file2.readlines()] 
    f1 += [item for item in f2 if item not in f1] 
    file1.seek(0) 
    for line in f1: 
     file1.write(line + '\n') 
1
使用 set也許有點短

類似的解決方案...

with open('one.txt', 'r+') as f_one, open('two.txt', 'r') as f_two: 
    res = sorted(set(f_one) | set(f_two)) 
    f_one.seek(0) 
    f_one.writelines(res)