python 将文件分割为指定大小的文件
将文件分割为指定大小的多个小文件
import sys, os
def split_file(file_path, to_dir, file_size=10, file_name='new_data', suffix=".mp4"):
"""
1M = 1024 Kb = 1024*1024 bate
"""
chunk_size = file_size * 1024 * 1024
if not os.path.exists(to_dir): # check whether todir exists or not
os.mkdir(to_dir)
else:
for file in os.listdir(to_dir):
os.remove(os.path.join(to_dir, file))
part_number = 0
input_file = open(file_path, 'rb') # open the fromfile
split_files = {}
while True:
chunk = input_file.read(chunk_size)
if not chunk: # check the chunk is empty
break
part_number += 1
new_file_path = os.path.join(to_dir, ('%s_%04d%s' % (file_name, part_number, suffix)))
file_obj = open(new_file_path, 'wb') # make partfile
file_obj.write(chunk) # write data into partfile
file_obj.close()
split_files["%04d" % part_number] = new_file_path
return split_files