Python实现将一个文件夹下面的多个txt文件合并成一个txt文件
程序员文章站
2022-03-22 08:10:34
...
import os
import shutil #导入这个包
txtpath='/CNN/txtpath'
namelist=[x for x in os.listdir(txtpath)]
namelist.sort(key=lambda x:int(x[:-4])) #txt file name
print len(namelist)#1674
outfilename='/CNN/b.txt'
outfile=open(outfilename,'a')#a没有文件可以创建
for i in range( len(namelist) ):
datapath = os.path.join(txtpath, namelist[i])
print datapath
file=open(datapath,'r')
shutil.copyfileobj(file,outfile)
file.close()
outfile.close()