python读取文件夹下所有txt_Python实现合并同一个文件夹下所有txt文件的方法

这篇文章主要介绍了Python实现合并同一个文件夹下所有txt文件的方法,涉及Python针对文件的遍历、读取、写入等相关操作技巧,需要的朋友可以参考下

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

一、需求分析

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

5c7e39e2d6ab96b23bd51916b337a681-0.jpg

5c7e39e2d6ab96b23bd51916b337a681-1.png

a003106162ec8145f1c8a2a02b781a58-2.png

二、合并效果

a003106162ec8145f1c8a2a02b781a58-3.jpg

a003106162ec8145f1c8a2a02b781a58-4.png

三、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相关内容感兴趣的读者可查看本站专题:《Python文本文件操作技巧汇总》、《Python文件与目录操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

相关推荐:

以上就是Python实现合并同一个文件夹下所有txt文件的方法的详细内容,更多请关注php中文网其它相关文章!

article_wechat2021.jpg?1111

本文原创发布php中文网,转载请注明出处,感谢您的尊重!