在爬取起点小说之后,同一个文件夹里有多条txt文件,如下图,笔者想到要将目录中的txt文件合并为一个目录的txt文件方便观看目录,于是开始动手做。
代码如下:
import os
def ListFilesToTxt(dir, file, wildcard, recursion):
exts = wildcard.split(" ")
files = os.listdir(dir)
for name in files:
fullname = os.path.join(dir, name) ##把目录和文件名生成一个目录
if (os.path.isdir(fullname) & recursion): #判断路径是否为文件夹
ListFilesToTxt(fullname, file, wildcard, recursion)
else:
for ext in exts:
if (name.endswith(ext)):
file.write(name + "\n")
break
def Test():
dir = "../爬取起点小说_语音识别/凡人修仙之仙界篇"
outfile = "..u/爬取起点小说_语音识别/凡人修仙之仙界篇/binaries.txt"
wildcard = ".txt .exe .dll .lib"
file = open(outfile, "w")
if not file:
print("cannot open the file %s for writing" % outfile)
ListFilesToTxt(dir, file, wildcard, 1)
file.close()
Test()
dir = "D:/软件(学习)/Python/TanZhou/爬取起点小说_语音识别"
print(os.listdir(dir))
运行结果如下:
txt文件展示,成功!