python核心编程学习笔记-2016-08-02-01-读取文件的函数中的文件指针问题

习题9-6

代码:

#-*-coding: utf-8-*-

def getInput():
    while True:
        try:
            filename = raw_input("Enter a filename: ")
            f = open(filename, 'r')
        except IOError:
            print "The file doesn't exit!"
        else:
            return f

def compare(f1, f2):
    comp = zip(f1.xreadlines(), f2.xreadlines())
    f1.seek(0) # 每次操作文件的时候要注意文件指针,如果没有seek,该函数在第一次调用时不会出现问题,但是此时文件指针已经指向文件末尾,第二次再调用该函数时,文件指针从文件末尾开始读起,自然生成[],导致两次函数调用结果不一致
    f2.seek(0)
    is_same = True
    for i in range(len(comp)):
        length = max(len(comp[i][0]), len(comp[i][1]))
        for j in range(length):
            if comp[i][0][j] != comp[i][1][j]:
                is_same = False
                row = i
                col = j
                break
        if not is_same:
            break
    if is_same:
        return
    else:
        return (row, col)

if __name__ == "__main__":
    f1 = getInput()
    f2 = getInput()   
    if compare(f1, f2) :
        print "file f1 is differ from f2."
        print "The first difference in {0} row and {1} col.".format(*compare(f1, f2))
    else:
        print "flie f1 and file f2 have the same content."
    f1.close()
    f2.close()
切记注释中的问题。

你可能感兴趣的:(python核心编程,python,编程)