txt大文件拆分(批量版)

发布于:2024-04-28 ⋅ 阅读:(28) ⋅ 点赞:(0)

之前的python程序只能拆分单个文件,这里重新加了个文件夹拆分的功能(打包好的exe文件在文章末尾)
使用步骤:运行代码–>把文件放到input文件夹里–>命令行界面回车–>output文件夹输出文件


outputPath = "./output" #文件夹目录
def split(inputPath, file):
    # 读取源文件,文件名最好加上绝对路径
    with open(inputPath+"/"+file, 'r') as f:
        # 把数据写入列表
        wordlist = f.readlines()
        # 算出总行数
        length = len(wordlist)
    # 设置每个拆分文件的行数
    unit = 1048576
    # 计算新文件的个数,如果总行数整除新文件行数,就取这个商的值,如果不整除,取商加1的值
    file_amount = length // unit + 1 if length % unit > 0 else length // unit
    # 分离文件名和后缀
    (name, suffix) = os.path.splitext(file)
    # 遍历所有新文件
    for num in range(file_amount):
        # 计算新文件中第一行在源文件中对应的行号
        start = num * unit
        # 计算新文件中最后一行在源文件中对应的行号
        end = length if length < (num + 1) * unit else (num + 1) * unit
        # 写入新文件,文件名最好加上绝对路径
        with open(outputPath+"/"+name + str(num + 1) + '.txt', 'w+') as f:
            # 遍历新文件的所有行
            for i in range(start, end):
                # 把列表中的数据写入新文件
                f.write(wordlist[i])

import os
inputPath = "./input" #文件夹目录
def main():
    # 创建文件夹,用于存放待分割的大文件
    if not os.path.exists(inputPath):
        os.makedirs(inputPath)
        print("Folder created")
    else:
        print("Folder already exists")
        
    # 创建文件夹,用于存放分割后的小文件
    if not os.path.exists(outputPath):
        os.makedirs(outputPath)
        print("Folder created")
    else:
        print("Folder already exists")

    Enter = input("请将待分割文件放于input文件夹下,再切换命令行界面,回车")
    
    #遍历文件夹内所有文件
    files= os.listdir(inputPath) #得到文件夹下的所有文件名称
    for file in files: #遍历文件夹
        if not os.path.isdir(file): #判断是否是文件夹,不是文件夹才打开
            split(inputPath, file); #分割文件


if __name__ == '__main__':
    main()

注:可以使用python打包exe命令,得到exe程序文件(Pyinstaller -F split.py),exe文件下载地址(链接:https://pan.baidu.com/s/18nw2p87NLUSBuyBVZbmqKg 提取码:sf6v)


网站公告

今日签到

点亮在社区的每一天
去签到