将一个文件夹内所有txt文件合并成一个txt文件。
合并后的txt文件按章节对应原来每个txt文件,一个输入文件是一章,章节名字就是原txt文件文件名。
import os
dirPath = "dirpath" #所有txt位于的文件夹路径
files = os.listdir(dirPath)
res = ""
i = 0
for file in files:
if file.endswith(".txt"):
i += 1
title = "第%s章 %s" % (i, file[0:len(file)-4])
with open("dirpath/" + file, "r", encoding='utf-8') as file:
content = file.read()
file.close()
append = "\n%s\n\n%s" % (title, content)
res += append
with open("dirpath/outfile.txt", "w", encoding='utf-8') as outFile:
outFile.write(res)
outFile.close()
print(len(res))
若用ipython notebook执行,启动用以下命令:
ipython notebook --NotebookApp.iopub_data_rate_limit=2147483647