按照行数分割txt文件
要求源文件行数为目标行数的整数倍
如图:每8行划分为1个文件;
代码
import os
import re
import sys
#------------------------按照行数划分文件-----------------------#
src_filepath = r'C:\\Users\\xxx\\Desktop\\python\\divide_file'
dst_filepath = r'C:\\Users\\xxx\\Desktop\\python\\divide_file'
size = 8 # 多少行一个文件
src_filename = 'test.txt'
dst_filename = 'dstfile_'
#-----------------------#
with open(src_filepath + os.path.sep + src_filename, 'r') as f1:
lines = f1.readlines()
length = len(lines) #源文件总行数
start = 0
end = size
for i in range(length//size):
#print(''.join(lines[start:end]))
outfile_name = dst_filename + '%02d'%i + '.txt'
with open(dst_filepath + os.path.sep + outfile_name, 'w') as f2:
f2.write(''.join(lines[start:end])) #!!!
start = start + size
end = end + size
#os.system("tail -n " + str(length % size) + " " + filepath + " > out_left.txt")