# -*- coding: utf-8 -*-
"""
Created on Wed Feb 22 13:40:03 2017
@author: Administrator
"""
import sys
def readFile(filename): ##读文件
re = {}
for line in open(filename):
arr = line.strip().split(‘\t‘) # s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符;
#1. 当rm为空时,默认删除空白符(包括‘\n‘, ‘\r‘, ‘\t‘, ‘ ‘)
#2.这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉
if len(arr)<=2:
continue
key = arr[0] + ‘_‘ + arr[1]
re.setdefault(key, arr[2]) #dict.setdefault(key, default=None),
#key——查找的键值;default——键不存在时,设置的默认键值
return re
def Minus(baseFile, otherFile): #对于第二份文件:第一份与第二份不相同,以第二份为主;
#第一份存在,第二份不存在,修改为0;第一份不存在,第二份存在,以第二份为主
re = {}
baseDict = readFile(baseFile)
otherDict = readFile(otherFile)
for k,v in baseDict.items():
if k in otherDict:
if not baseDict[k].isdigit() or not otherDict[k].isdigit():
continue
c = int(baseDict[k]) - int(otherDict[k])
if c != 0:
re[k] = otherDict[k]
continue
if k not in otherDict:
if not baseDict[k].isdigit() :
continue
c = 0
re[k] = str(c)
continue
for k,v in otherDict.items():
if k not in baseDict:
if not otherDict[k].isdigit():
continue
re[k] = otherDict[k]
return re
def writeFile(baseDict):
for k,v in baseDict.items(): #dict = { 1 : 2, ‘a‘ : ‘b‘, ‘hello‘ : ‘world‘ }
#dict.items() [(‘a‘, ‘b‘), (1, 2), (‘hello‘, ‘world‘)]
arr = k.split(‘_‘)
print "%s\t%s\t%s" % (arr[0], arr[1], v)
def main():
baseFile = r‘one.txt‘
otherFile = r‘two.txt‘
baseDict = Minus(baseFile, otherFile)
writeFile(baseDict)
if __name__==‘__main__‘:
main()
#####################################################
######################案例###########################
one.txt
1 2 3
4 5 6
7 8 9
10 11 12
two.txt
1 2 3
7 8 9
10 11 8
13 14 15
输出
13 14 15
10 11 8
4 5 0