2016-05-06 11 views
1

私はPythonの2つのテキストファイルを比較し、その2つの違いを表示するコードを作成しています。私はセットを使うように言われました。手動でファイル名を入力するのではなく、ファイルを選択するダイアログボックスを持つことも可能ですか?私は非常に初心者レベルのPythonですので、コードを書くことができれば、本当に感謝しています。Pythonの2つのファイルの違いを見つける

FILE1.TXT

hamburgers 
potatoes 
avocado 
grapes 
seaweed 

FILE2.TXT

cheeseburgers 
potatoes 
peanuts 
grapes 
seaweed 

ので、私はこれがそれだ場合、私は持っているが、わからないものです

コードが チーズバーガー、ピーナッツを印刷したいです右:

old_path = 'File1.txt' 
new_path = 'File2.txt' 

old_lines = file(old_path).read().split('\n') 
new_lines = file(new_path).read().split('\n') 

old_lines_set = set(old_lines) 
new_lines_set = set(new_lines) 

old_added = old_lines_set - new_lines_set 
old_removed = new_line_set - old_lines_set 

for line in old_lines: 
    if line in old_added: 
     print '-' , line.strip() 
    elif line in old_removed: 
     print '+' , line.strip() 

for line in new_lines: 
    if line in old added: 
     print '-' , line.strip() 
    elif line in old_removed: 
     print '+' , line.strip() 
+0

あなたはどんな出力を得ますか? – Ashish

答えて

2
doc = open(filename, 'r') 
doc1 = open(filename, 'r') 

f1 = [x for x in doc.readlines()] 
f2 = [x for x in doc1.readlines()] 

diff = [line for line in f1 if line not in f2] # lines present only in f1 
diff1 = [line for line in f2 if line not in f1] # lines present only in f2 

doc.close() 
doc1.close() 
+1

OPは、特に大容量ファイルの場合は非常に非効率的であることに注意してください。 – Goodies

1

内蔵の設定機能を使用して簡単に解決策は、:

a = set(['hamburgers', 'potatoes', 'avocado', 'grapes', 'seaweed']) 
b = set(['cheeseburgers', 'potatoes', 'peanuts', 'grapes', 'seaweed']) 
a.difference(b) 
b.difference(a) 

set.difference()関数は、あなたが望むとおりに処理できる、あなたがもう一度オブジェクトを設定できます。 [私はあなたの宿題を解決していないことを願って] ...

関連する問題