您的位置:首页 > 编程语言 > Python开发

python实现分割文件

2015-04-12 10:48 211 查看
我们有时候需要对大文件进行分割,从而就可以在记事本等软件中打开以便好做处理,现在使用Python实现一个文件分割的功能,可以按照指定的大小分割文件为一系列子文件。

见代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os

def split_file(filename,size):
fp=open(filename,'rb')
i=0
n=0
dir_put='split_dir/'
if os.path.isdir(dir_put):
pass
else:
os.mkdir(dir_put)
filename_front=os.path.splitext(filename)[0]   #取到除去扩展名的文件名
temp=open(dir_put+filename_front+'.part'+str(i)+'.txt','wb')
buf=fp.read(1024)
while 1:
temp.write(buf)
buf=fp.read(1024)
if buf=='':
print filename_front+'.part'+str(i)+'.txt'
temp.close()
fp.close()
return
n+=1
if n==size:
n=0
print filename_front+'.part'+str(i)+'.txt'
i+=1
temp.close()
temp=open(dir_put+filename_front+'.part'+str(i)+'.txt','wb')
fp.close()

if __name__=='__main__':
filename=raw_input("enter filename:")
size=int(raw_input("enter size:"))   #注意转换为int,否则无效
split_file(filename,size)  #第二个参数的单位是k
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: