我有两个文本文件,名称是one.txt和two.txt 在one.txt中,内容是
AAA
BBB
CCC
DDD
在two.txt中,内容为
DDD
EEE
我想要一个python代码来确定one.txt中是否包含two.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 :(得分: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 :(得分:1)
这应该这样做:
$(currentResult).fadeOut("slow").promise().done(function(){
$(currentResult).hide().insertBefore($(relevantResults[j])).fadeIn('slow');
});
答案 2 :(得分: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)