Python实现合并同一个文件夹下所有txt文件的方法示例

时间:2022-01-29 20:26:11

本文实例讲述了Python实现合并同一个文件夹下所有txt文件的方法。分享给大家供大家参考,具体如下:

一、需求分析

合并一个文件夹下所有txt文件

Python实现合并同一个文件夹下所有txt文件的方法示例

Python实现合并同一个文件夹下所有txt文件的方法示例

Python实现合并同一个文件夹下所有txt文件的方法示例

二、合并效果

Python实现合并同一个文件夹下所有txt文件的方法示例

Python实现合并同一个文件夹下所有txt文件的方法示例

三、python实现代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# -*- 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程序设计有所帮助。

原文链接:https://blog.csdn.net/u013421629/article/details/77712630