python 比較兩個檔案交集 並集 差集

2021-09-02 18:00:03 字數 1663 閱讀 3684

python 比價兩個檔案交集、並集、差集

#!/usr/bin/env python2.7

#coding=utf-8

'''s05=set(['x','b','a'])

s06=set(['c','x','e'])

'''s05=set(open('/users/.../1205.txt','r').readlines())

s06=set(open('/users/.../1206.txt','r').readlines())

output=true

path='/users/ban/downloads/rmcompare.txt'

print '集合比較'

result=s06&s05

print '----結果----'

n = len(result)

print 'n='+str(n)

if n>0 and n<100:

for item in result:

print item

print '----結果----'

if output:

print '輸出結果'

f = open(path,'w')

f.writelines(result)

f.close

print '檔案路徑'+path

print 'done!'

'''一、授予執行許可權:

cd /users/ban/downloads

chmod 777 compare.py

ls -all | grep compare.py

二、執行:

./compare.py

三、集合比價例項:

a = t | s # t 和 s的並集

b = t & s # t 和 s的交集

c = t – s # 求差集(項在t中,但不在s中)

d = t ^ s # 對稱差集(項在t或s中,但不會同時出現在二者中)

四、檔案讀寫例項:

>>> f = open('test.txt', 'w') # 若是'wb'就表示寫二進位制檔案

>>> f.write('hello, world!')

>>> f.close()

python檔案物件提供了兩個「寫」方法: write() 和 writelines()。

write()方法和read()、readline()方法對應,是將字串寫入到檔案中。

writelines()方法和readlines()方法對應,也是針對列表的操作。它接收乙個字串列表作為引數,將他們寫入到檔案中,換行符不會自動的加入,因此,需要顯式的加入換行符。

關於open()的mode引數:

'r':讀

'w':寫

'a':追加

'r+' == r+w(可讀可寫,檔案若不存在就報錯(ioerror))

'w+' == w+r(可讀可寫,檔案若不存在就建立)

'a+' ==a+r(可追加可寫,檔案若不存在就建立)

對應的,如果是二進位制檔案,就都加乙個b就好啦:

'rb'  'wb'  'ab'  'rb+'  'wb+'  'ab+'

'''

linux shell求兩個檔案的差 並 交集

比較兩個檔案 a.txt 11 2341 b.txt 56 121 使用命令comm比較,輸入檔案必須為有序 列之間使用製表符 t分隔 comm sort a.txt sort b.txt 11 1234 56 第一列為a與b的差集 a.txt b.txt comm sort a.txt sort ...

python 兩個list 交集 並集 差集

def aaaaa a1 2 3,4 5 b1 2 5,8 a set a1 b set b1 ai a.intersection b print 交集 兩個list都有的元素.ai au a.union b print 並集 合併list,並且去除重複元素.au ad a.difference b...

python 比較兩個json並返回差別

現在要比較兩個json是否相等,若不同則返回差別 比如下面dict資料的對比 dict1 dict2 對比兩個dict是否相等 for src list,dst list in zip sorted dict1 sorted dict2 ifstr dict1 src list str dict2 ...