本文实例讲述了Python实现合并同一个文件夹下所有txt文件的方法。分享给大家供大家参考,具体如下:
一、需求分析
合并一个文件夹下所有txt文件
	
	
	
二、合并效果
	
	
三、python实现代码
# -*- coding:utf-8*-import sysreload(sys)sys.setdefaultencoding('utf-8')import osimport os.pathimport timetime1=time.time()##########################合并同一个文件夹下多个txt################def MergeTxt(filepath,outfile):  k = open(filepath+outfile, 'a+')  for parent, dirnames, filenames in os.walk(filepath):    for filepath in filenames:      txtPath = os.path.join(parent, filepath) # txtpath就是所有文件夹的路径      f = open(txtPath)      ##########换行写入##################      k.write(f.read()+"/n")  k.close()  print "finished"if __name__ == '__main__':  filepath="D:/course/"  outfile="result.txt"  MergeTxt(filepath,outfile)  time2 = time.time()  print u'总共耗时:' + str(time2 - time1) + 's'运行结果:
"D:/Program Files/Python27/python.exe" D:/PycharmProjects/learn2017/合并多个txt.py
finished
总共耗时:0.000999927520752s
Process finished with exit code 0
希望本文所述对大家Python程序设计有所帮助。
新闻热点
疑难解答