首页 > 编程 > Python > 正文

Python实现分割文件及合并文件的方法

2020-01-04 18:06:12
字体:
来源:转载
供稿:网友

这篇文章主要介绍了Python实现分割文件及合并文件的方法,涉及Python针对文件的分割与合并操作相关技巧,通过自定义函数split与join实现了文件的分割与合并操作,需要的朋友可以参考下

本文实例讲述了Python实现分割文件及合并文件的方法。分享给大家供大家参考。具体如下:

分割文件split.py如下:

 

 
  1. #!/usr/bin/python 
  2. ########################################################################## 
  3. # split a file into a set of parts; join.py puts them back together; 
  4. # this is a customizable version of the standard unix split command-line  
  5. # utility; because it is written in Python, it also works on Windows and 
  6. # can be easily modified; because it exports a function, its logic can  
  7. # also be imported and reused in other applications; 
  8. ########################################################################## 
  9. import sys, os 
  10. kilobytes = 1024 
  11. megabytes = kilobytes * 1000 
  12. chunksize = int(1.4 * megabytes) # default: roughly a floppy 
  13. def split(fromfile, todir, chunksize=chunksize):  
  14. if not os.path.exists(todir): # caller handles errors 
  15. os.mkdir(todir) # make dir, read/write parts 
  16. else
  17. for fname in os.listdir(todir): # delete any existing files 
  18. os.remove(os.path.join(todir, fname))  
  19. partnum = 0 
  20. input = open(fromfile, 'rb') # use binary mode on Windows 
  21. while 1: # eof=empty string from read 
  22. chunk = input.read(chunksize) # get next part <= chunksize 
  23. if not chunk: break 
  24. partnum = partnum+1 
  25. filename = os.path.join(todir, ('part%04d' % partnum)) 
  26. fileobj = open(filename, 'wb'
  27. fileobj.write(chunk) 
  28. fileobj.close() # or simply open().write() 
  29. input.close() 
  30. assert partnum <= 9999 # join sort fails if 5 digits 
  31. return partnum 
  32. if __name__ == '__main__'
  33. if len(sys.argv) == 2 and sys.argv[1] == '-help'
  34. print 'Use: split.py [file-to-split target-dir [chunksize]]' 
  35. else
  36. if len(sys.argv) < 3: 
  37. interactive = 1 
  38. fromfile = raw_input('File to be split? ') # input if clicked  
  39. todir = raw_input('Directory to store part files? '
  40. else
  41. interactive = 0 
  42. fromfile, todir = sys.argv[1:3] # args in cmdline 
  43. if len(sys.argv) == 4: chunksize = int(sys.argv[3]) 
  44. absfrom, absto = map(os.path.abspath, [fromfile, todir]) 
  45. print 'Splitting', absfrom, 'to', absto, 'by', chunksize 
  46. try
  47. parts = split(fromfile, todir, chunksize) 
  48. except: 
  49. print 'Error during split:' 
  50. print sys.exc_info()[0], sys.exc_info()[1] 
  51. else
  52. print 'Split finished:', parts, 'parts are in', absto 
  53. if interactive: raw_input('Press Enter key') # pause if clicked 

合并文件join_file.py如下:

 

 
  1. #!/usr/bin/python 
  2. ########################################################################## 
  3. # join all part files in a dir created by split.py, to recreate file.  
  4. # This is roughly like a 'cat fromdir/* > tofile' command on unix, but is  
  5. # more portable and configurable, and exports the join operation as a  
  6. # reusable function. Relies on sort order of file names: must be same  
  7. # length. Could extend split/join to popup Tkinter file selectors. 
  8. ########################################################################## 
  9. import os, sys 
  10. readsize = 1024 
  11. def join(fromdir, tofile): 
  12. output = open(tofile, 'wb'
  13. parts = os.listdir(fromdir) 
  14. parts.sort() 
  15. for filename in parts: 
  16. filepath = os.path.join(fromdir, filename) 
  17. fileobj = open(filepath, 'rb'
  18. while 1: 
  19. filebytes = fileobj.read(readsize) 
  20. if not filebytes: break 
  21. output.write(filebytes) 
  22. fileobj.close() 
  23. output.close() 
  24. if __name__ == '__main__'
  25. if len(sys.argv) == 2 and sys.argv[1] == '-help'
  26. print 'Use: join.py [from-dir-name to-file-name]' 
  27. else
  28. if len(sys.argv) != 3: 
  29. interactive = 1 
  30. fromdir = raw_input('Directory containing part files? '
  31. tofile = raw_input('Name of file to be recreated? '
  32. else
  33. interactive = 0 
  34. fromdir, tofile = sys.argv[1:] 
  35. absfrom, absto = map(os.path.abspath, [fromdir, tofile]) 
  36. print 'Joining', absfrom, 'to make', absto 
  37. try
  38. join(fromdir, tofile) 
  39. except: 
  40. print 'Error joining files:' 
  41. print sys.exc_info()[0], sys.exc_info()[1] 
  42. else
  43. print 'Join complete: see', absto 
  44. if interactive: raw_input('Press Enter key') # pause if clicked 

希望本文所述对大家的Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表