首页 > 编程语言 > 详细

python练习题-9-6

时间:2019-12-10 22:01:26      阅读:84      评论:0      收藏:0      [点我收藏+]

本代码是《Python核心编程(第二版)》第九章的9-6练习题,完成的功能为:文件比较:比较两个文本文件是否相同,如果不同,给出第一个不同处的行号和列号。

 1 #!/usr/bin/env python
 2 #-*- coding: utf-8 -*-
 3 
 4 
 5 #文件比较:比较两个文本文件是否相同,如果不同,给出第一个不同处的行号和列号
 6 def func_9_6():
 7     choice1 = raw_input("Enter one filename: ")
 8     choice2 = raw_input("Enter another filename: ")
 9     if choice1 == ‘‘ or choice2 == ‘‘:
10         return
11     f1 = open(choice1)
12     f2 = open(choice2)
13     lines1 = f1.readlines()
14     lines2 = f2.readlines()
15     lines_tmp1 = len(lines1) if len(lines1) < len(lines2) else len(lines2)
16     for i in range(lines_tmp1):
17         if lines1[i] == lines2[i]:
18             continue
19         lines_tmp2 = len(lines1[i]) if len(lines1[i]) < len(lines2[i]) else len(lines2[i])
20         for j in range(lines_tmp2):
21             if lines1[i][j] == lines2[i][j]:
22                 continue
23             else:
24                 print %s is not equal of %s, col:%d raw:%d\n % (choice1, choice2, i+1, j+1)
25     if  len(lines1) == len(lines2) and i == lines_tmp1-1:
26         print %s is equal of %s\n % (choice1, choice2)  
27 
28 def showmenu():
29     while True:
30         choice = raw_input("Enter question num, (Q)uit: ")
31         if choice.lower() == q:
32             break
33         if choice == 9-6:
34             func_9_6()
35 
36 if __name__ == __main__:
37     showmenu()

测试结果:

 1 [root@192 python_code]# python file_operate.py 
 2 Enter question num, (Q)uit: 9-6
 3 Enter one filename: testfile  
 4 Enter another filename: testfile
 5 testfile is equal of testfile
 6 
 7 Enter question num, (Q)uit: 9-6
 8 Enter one filename: testfile
 9 Enter another filename: myfile
10 testfile is not equal of myfile, col:1 raw:6
11 
12 Enter question num, (Q)uit: 

两个文件testfile和myfile的内容如下:

[root@192 python_code]# more testfile 
hello
world
[root@192 python_code]# more myfile 
helloworld
[root@192 python_code]# 

 

python练习题-9-6

原文:https://www.cnblogs.com/mrlayfolk/p/12019431.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!