这篇文章主要介绍了python实现合并同一个文件夹下所有txt文件的方法,涉及python针对文件的遍历、读取、写入等相关操作技巧,需要的朋友可以参考下
本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《python文本文件操作技巧汇总》、《python文件与目录操作技巧汇总》、《python编码操作技巧总结》、《python数据结构与算法教程》、《python函数使用技巧总结》、《python字符串操作技巧汇总》及《python入门与进阶经典教程》
相关推荐:
python实现对指定输入的字符串逆序输出的方法
python实现按当前日期(年、月、日)创建多级目录的方法
python实现的计算器功能
以上就是python实现合并同一个文件夹下所有txt文件的方法的详细内容。