前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 文件分割 脚本

python 文件分割 脚本

作者头像
用户5760343
发布2022-05-13 11:10:00
8260
发布2022-05-13 11:10:00
举报
文章被收录于专栏:sktj

!/usr/bin/python

""" ################################################################################ split a file into a set of parts; join.py puts them back together; this is a customizable version of the standard Unix split command-line utility; because it is written in Python, it also works on Windows and can be easily modified; because it exports a function, its logic can also be imported and reused in other applications; ################################################################################ """

import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy

def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while True: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum += 1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open().write() input.close() assert partnum <= 9999 # join sort fails if 5 digits return partnum

if name == 'main': if len(sys.argv) == 2 and sys.argv[1] == '-help': print('Use: split.py [file-to-split target-dir [chunksize]]') else: if len(sys.argv) < 3: interactive = True fromfile = input('File to be split? ') # input if clicked todir = input('Directory to store part files? ') else: interactive = False fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print('Splitting', absfrom, 'to', absto, 'by', chunksize)

代码语言:javascript
复制
    try:
        parts = split(fromfile, todir, chunksize)
    except:
        print('Error during split:')
        print(sys.exc_info()[0], sys.exc_info()[1])
    else:
        print('Split finished:', parts, 'parts are in', absto)
    if interactive: input('Press Enter key') # pause if clicked
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • !/usr/bin/python
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档