將一個文件夾內所有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