python文件比较示例分享

yipeiwu_com6年前Python基础

复制代码 代码如下:

# 比较两个字符串,如果不同返回第一个不相同的位置
# 如果相同返回0
def cmpstr(str1, str2):
    col = 0
    for c1, c2 in zip(str1, str2):
        if c1 == c2:
            col += 1
            continue
        else :
            break

    #判断是怎样退出循环的,还有一种情况是串长度不同
    if c1 != c2 or len(str1) != len(str2):
        return col+1
    else :
        return 0

file1 = open("a.txt",'r')
file2 = open("b.txt",'r')

fa = file1.readlines()
fb = file2.readlines()
file1.close()
file2.close()

#用GBK解码,这样可以处理中文字符
fa = [ str.decode("gbk") for str in fa]
fb = [ str.decode("gbk") for str in fb]

row = 0
col = 0


#开始比较两个文件的内容
for str1, str2 in zip(fa, fb):
    col = cmpstr(str1,str2)
    # col=0则说明两行相等
    if col == 0 :
        row += 1
        continue
    else:
        break

#如果有一行不同,或者文件长度不一样
if str1 != str2 or len(fa) != len(fb):
    #打印出不同的行序和列序,并把不同的前一句后本句打印出来
    #最后两个字符是不同的地方
    print "row:", row+1, "col:", col
    print "file a is:\n", fa[row-1],fa[row][:col+1], "\n"
    print "file b is:\n", fb[row-1],fb[row][:col+1], "\n"
else :
    print "All are same!"

raw_input("Press Enter to exit.")  

相关文章

pytorch 实现tensor与numpy数组转换

看代码,tensor转numpy: a = torch.ones(2,2) b = a.numpy() c=np.array(a) #也可以转numpy数组 print(type(a...

Python编程实现从字典中提取子集的方法分析

本文实例讲述了Python编程实现从字典中提取子集的方法。分享给大家供大家参考,具体如下: 首先我们会想到使用字典推导式(dictionary comprehension)来解决这个问题...

简单学习Python多进程Multiprocessing

简单学习Python多进程Multiprocessing

1.1 什么是 Multiprocessing 多线程在同一时间只能处理一个任务。 可把任务平均分配给每个核,而每个核具有自己的运算空间。 1.2 添加进程 Process 与线程类似,...

Python SQLite3数据库日期与时间常见函数用法分析

本文实例讲述了Python SQLite3数据库日期与时间常见函数。分享给大家供大家参考,具体如下: import sqlite3 #con = sqlite3.connect('e...

Python subprocess库的使用详解

介绍 使用subprocess模块的目的是用于替换os.system等一些旧的模块和方法。 运行python的时候,我们都是在创建并运行一个进程。像Linux进程那样,一个进程可以f...