本文實例講述了Python實現合并同一個文件夾下所有txt文件的方法。分享給大家供大家參考,具體如下:
一、需求分析
合并一個文件夾下所有txt文件
二、合并效果
三、python實現代碼
# -*- coding:utf-8*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import os.path
import time
time1=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程序設計有所幫助。