我是靠谱客的博主 坦率荔枝,这篇文章主要介绍Python:将多个txt文件合并为一个txt文件,现在分享给大家,希望可以做个参考。

将一个文件夹内所有txt文件合并成一个txt文件。

合并后的txt文件按章节对应原来每个txt文件,一个输入文件是一章,章节名字就是原txt文件文件名。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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%snn%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执行,启动用以下命令:

复制代码
1
2
ipython notebook --NotebookApp.iopub_data_rate_limit=2147483647

转载于:https://www.cnblogs.com/xuejianbest/p/10285119.html

最后

以上就是坦率荔枝最近收集整理的关于Python:将多个txt文件合并为一个txt文件的全部内容,更多相关Python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部