本代码是《Python 核心编程 (第二版)》第九章的 9-6 练习题, 完成的功能为: 文件比较: 比较两个文本文件是否相同, 如果不同, 给出第一个不同处的行号和列号.
- #!/usr/bin/env python
- #-*- coding: utf-8 -*-
- #文件比较: 比较两个文本文件是否相同, 如果不同, 给出第一个不同处的行号和列号
- def func_9_6():
- choice1 = raw_input("Enter one filename:")
- choice2 = raw_input("Enter another filename:")
- if choice1 == ''or choice2 =='':
- return
- f1 = open(choice1)
- f2 = open(choice2)
- lines1 = f1.readlines()
- lines2 = f2.readlines()
- lines_tmp1 = len(lines1) if len(lines1) < len(lines2) else len(lines2)
- for i in range(lines_tmp1):
- if lines1[i] == lines2[i]:
- continue
- lines_tmp2 = len(lines1[i]) if len(lines1[i]) < len(lines2[i]) else len(lines2[i])
- for j in range(lines_tmp2):
- if lines1[i][j] == lines2[i][j]:
- continue
- else:
- print '%s is not equal of %s, col:%d raw:%d\n' % (choice1, choice2, i+1, j+1)
- if len(lines1) == len(lines2) and i == lines_tmp1-1:
- print '%s is equal of %s\n' % (choice1, choice2)
- def showmenu():
- while True:
- choice = raw_input("Enter question num, (Q)uit:")
- if choice.lower() == 'q':
- break
- if choice == '9-6':
- func_9_6()
- if __name__ == '__main__':
- showmenu()
测试结果:
- [[email protected] python_code]# python file_operate.py
- Enter question num, (Q)uit: 9-6
- Enter one filename: testfile
- Enter another filename: testfile
- testfile is equal of testfile
- Enter question num, (Q)uit: 9-6
- Enter one filename: testfile
- Enter another filename: myfile
- testfile is not equal of myfile, col:1 raw:6
- Enter question num, (Q)uit:
两个文件 testfile 和 myfile 的内容如下:
- [[email protected] python_code]# more testfile
- hello
- world
- [[email protected]192 python_code]# more myfile
- helloworld
- [[email protected]192 python_code]#
来源: http://www.bubuko.com/infodetail-3325828.html