我有两个文本文件。
file1.txt 具有:
gedit
google chrome
git
vim
foo
bar
file2.txt 具有:
firefox
svn
foo
vim
如何编写一个脚本,在执行时(使用file1.txt和file2.txt作为参数)检查每行<中的文本重复/strong> (我的意思是它应该按行处理),删除两个文件中的重复文本。
因此处理后,file1.txt和file2.txt都应具有以下内容:
gedit
google chrome
git
bar
firefox
svn
请注意,foo
和 vim
已从这两个文件中删除。
有什么指导吗?
最佳答案
with open('file1.txt','r+') as f1 ,open('file2.txt','r+') as f2:
file1=set(x.strip() for x in f1 if x.strip())
file2=set(x.strip() for x in f2 if x.strip())
newfile=file1.symmetric_difference(file2) #symmetric difference removes those values which are present in both sets, and returns a new set.
f2.truncate(0) #truncate the file to 0 bytes
f1.truncate(0)
f2.seek(0) # to push the cursor back to the starting pointing in the file.
f1.seek(0)
for x in newfile:
f1.write(x+'\n')
f2.write(x+'\n')
现在两个文件都包含:
svn
git
firefox
gedit
google chrome
bar
关于python - 如何删除两个文件中相同的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11168517/