Python实现合并同一个文件夹下所有txt文件的方法示例
作者:开心果汁 时间:2023-10-11 00:24:22
本文实例讲述了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程序设计有所帮助。
来源:https://blog.csdn.net/u013421629/article/details/77712630
标签:Python,合并,txt文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Python手写数字识别模型的构建与使用
2023-10-21 18:34:12
![](https://img.aspxhome.com/file/2023/2/100292_0s.png)
Python进程间通信Queue消息队列用法分析
2021-11-28 03:04:18
优化SQLServer数据库服务器内存配置的策略
2009-05-13 10:25:00
浅谈python中的实例方法、类方法和静态方法
2022-02-10 07:11:27
Python 中的json常见用法实例详解
2022-01-03 15:28:48
![](https://img.aspxhome.com/file/2023/2/124342_0s.png)
如何基于Python实现word文档重新排版
2023-06-09 11:19:24
![](https://img.aspxhome.com/file/2023/8/128468_0s.png)
JavaScript实现点击自制菜单效果
2024-05-02 17:24:53
![](https://img.aspxhome.com/file/2023/5/129785_0s.jpg)
基于DATAFRAME中元素的读取与修改方法
2021-11-18 03:59:09
python实现凯撒密码加密解密的示例代码
2021-12-08 07:29:07
Pandas中DataFrame对象转置(交换行列)
2023-06-11 05:01:45
![](https://img.aspxhome.com/file/2023/0/63520_0s.png)
零基础也能看懂的python内置csv模块教程
2023-01-06 14:03:16
![](https://img.aspxhome.com/file/2023/2/121692_0s.png)
MHA实现mysql主从数据库手动切换的方法
2024-01-25 22:36:23
破解空间实现域名绑定到子目录方法
2010-03-14 11:29:00
Python爬虫制作翻译程序的示例代码
2023-08-13 06:38:35
![](https://img.aspxhome.com/file/2023/5/78725_0s.jpg)
vscode检测到#include错误请更新includePath的解决方法
2022-10-14 22:58:04
![](https://img.aspxhome.com/file/2023/8/117498_0s.png)
TensorFlow索引与切片的实现方法
2022-11-08 16:00:12
![](https://img.aspxhome.com/file/2023/7/97517_0s.png)
Radio 单选JS动态添加的选项onchange事件无效的解决方法
2024-04-28 09:51:03
Pygame Draw绘图函数的具体使用
2021-05-24 12:14:49
![](https://img.aspxhome.com/file/2023/9/128589_0s.gif)
MySQL 统计查询实现代码
2024-01-25 06:41:14
使用jQuery向asp.net Mvc传递复杂json数据-ModelBinder篇
2024-06-05 09:32:20
![](https://img.aspxhome.com/file/2023/3/122783_0s.jpg)