txt大文件拆分(批量版)

时间:2024-04-28 07:38:53
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()