[python]:按照行数分割txt文件

按照行数分割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")



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值