Python:将多个txt文件合并为一个txt文件

Stella981
• 阅读 1592

将一个文件夹内所有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
点赞
收藏
评论区
推荐文章
Easter79 Easter79
2年前
svn本地文件夹断开服务器连接
使用svn进行版本控制,每个文件夹下都有.svn文件夹,有些项目在脱离svn版本控制之后,想删除项目中所有的.svn文件夹,可用下面的方法进行快速删除:建立一个文本文件,取名为killsvnfolders.reg(扩展名由txt改为reg),文件的内容如下:WindowsRegistryEditorVersion5.00
Easter79 Easter79
2年前
tar命令中的
我用这个命令:tarzcvfchao.tar.gz/chao/\ 打包文件的时候,在压缩包里把 /chao/这个路径也打包进去了。root@yunweitestchaols/chao/01.txt02.txt03.txt04.txt05.txt06.txt07.txt08.txt
Wesley13 Wesley13
2年前
java读取按行txt文件
importjava.io.BufferedReader;importjava.io.FileInputStream;importjava.io.InputStreamReader;publicclassT{publicstaticvoidmain(Stringargs
Wesley13 Wesley13
2年前
JAVA读写文件
1/23@Description:写文件4@param@paramurl要写到服务器的路径5@param@paramfileName要写的文件名需要加前缀如.txt6@par
Stella981 Stella981
2年前
DOS之del命令
基本del命令是用来删除一个或多个文件的,删除文件夹的话还要用rd命令。举个栗子:1.例如我们要删除C盘中的a.txt,我们就可以dela.txt1.也可以同时删除多个,用空格,逗号或分号分开文件名。dela.txtb.txt1.删除当前文件夹中所有后缀为x
Wesley13 Wesley13
2年前
JAVA获取txt文件内容
  JAVA读取txt文件内容  通常,我们可以直接通过文件流来读取txt文件的内容,但有时可能会出现乱码!此时只要设置一下文件字符编码即可。1importjava.io.BufferedReader;2importjava.io.File;3importjava.io
Stella981 Stella981
2年前
Shell对比两个文件中的记录有多少重复
问题是这样的:有两个uid的文件,格式如下:uid1.txt1234523456....uid2.txt1234534567....需要统计这两个文件中相同的uid有多少个。方法有两个:1.一个是读入一个文件的一行然后再另一个文件中找,找到就加一,shell大概是这样的(未测试)count0
Stella981 Stella981
2年前
Android 创建文件
publicclassCreateFiles{StringfilenameTempInfo.audioPath"/hhaudio"".txt";//创建文件夹及文件publicvoidCreateText()thro
Stella981 Stella981
2年前
SAS导入txt数据
众所周知,在我们进行数据处理分析的时候,不会是一直自己手动输入,这就要求从外部读取数据了。下边我们讲解从txt文件中将数据读取出来。我们读取的txt文件如下college\_inf.txt:depart_idnameagemajorlocationA101|cy|22|software1|beijing|B10
Stella981 Stella981
2年前
HanLP
停用词表的修改停用词表在“pyhanlp\\static\\data\\dictionary”路径下的“stopwords.txt”文件中,CoreStopWordDictionary.apply方法支持去除停用词。如果需要修改停用词表,则直接编辑文件“stopwords.txt”,之后删除路径下的“stopwords.txt.bin”,运行Co