VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python入门 >
  • python入门教程之Python3标准库:filecmp比较文件

本站最新发布   Python从入门到精通|Python基础教程
试听地址  
https://www.xin3721.com/eschool/pythonxin3721/


1. filecmp比较文件

filecmp模块提供了一些函数和一个类来比较文件系统上的文件和目录。

1.1 示例数据

使用下面代码创建一组测试文件。


  1. import os
  2.  
  3. def mkfile(filename, body=None):
  4. with open(filename, 'w') as f:
  5. f.write(body or filename)
  6. return
  7.  
  8. def make_example_dir(top):
  9. if not os.path.exists(top):
  10. os.mkdir(top)
  11. curdir = os.getcwd()
  12. os.chdir(top)
  13.  
  14. os.mkdir('dir1')
  15. os.mkdir('dir2')
  16.  
  17. mkfile('dir1/file_only_in_dir1')
  18. mkfile('dir2/file_only_in_dir2')
  19.  
  20. os.mkdir('dir1/dir_only_in_dir1')
  21. os.mkdir('dir2/dir_only_in_dir2')
  22.  
  23. os.mkdir('dir1/common_dir')
  24. os.mkdir('dir2/common_dir')
  25.  
  26. mkfile('dir1/common_file', 'this file is the same')
  27. os.link('dir1/common_file', 'dir2/common_file')
  28.  
  29. mkfile('dir1/contents_differ')
  30. mkfile('dir2/contents_differ')
  31. # Update the access and modification times so most of the stat
  32. # results will match.
  33. st = os.stat('dir1/contents_differ')
  34. os.utime('dir2/contents_differ', (st.st_atime, st.st_mtime))
  35.  
  36. mkfile('dir1/file_in_dir1', 'This is a file in dir1')
  37. os.mkdir('dir2/file_in_dir1')
  38.  
  39. os.chdir(curdir)
  40. return
  41.  
  42. if __name__ == '__main__':
  43. os.chdir(os.path.dirname(__file__) or os.getcwd())
  44. make_example_dir('example')
  45. make_example_dir('example/dir1/common_dir')
  46. make_example_dir('example/dir2/common_dir')

运行这个脚本会在axample目录下生成一个文件树。

common_dir目录下也有同样的目录结构,以提供有意思的递归比较选择。 

1.2 比较文件

cmp()用于比较文件系统上的两个文件。


  1. import filecmp
  2.  
  3. print('common_file :', end=' ')
  4. print(filecmp.cmp('example/dir1/common_file',
  5. 'example/dir2/common_file',
  6. shallow=True),
  7. end=' ')
  8. print(filecmp.cmp('example/dir1/common_file',
  9. 'example/dir2/common_file',
  10. shallow=False))
  11.  
  12. print('contents_differ:', end=' ')
  13. print(filecmp.cmp('example/dir1/contents_differ',
  14. 'example/dir2/contents_differ',
  15. shallow=True),
  16. end=' ')
  17. print(filecmp.cmp('example/dir1/contents_differ',
  18. 'example/dir2/contents_differ',
  19. shallow=False))
  20.  
  21. print('identical :', end=' ')
  22. print(filecmp.cmp('example/dir1/file_only_in_dir1',
相关教程