python中实现指定类型文件的合并
1、合并txt文件
[root@PC1 test2]# ls a.txt b.txt c.txt test.py x.csv y.csv [root@PC1 test2]# cat a.txt a a a b b b [root@PC1 test2]# cat b.txt c c c d d d [root@PC1 test2]# cat c.txt e e e f f f [root@PC1 test2]# cat x.csv 8 9 4 2 3 9 [root@PC1 test2]# cat y.csv 8 4 2 2 4 8 [root@PC1 test2]# cat test.py #!/usr/bin/python out_file = open("result.txt", "w") ## 输出文件 import os ## 导入os模块 for i in os.listdir(): ## 遍历当前目录 if i.endswith(".txt"): ## 判断文件是否是txt文件 tmp_file = open(i, "r") ## 打开txt文件 for j in tmp_file: out_file.write(j) ## 写入 tmp_file.close() ## 关闭txt文件 out_file.close() [root@PC1 test2]# python test.py [root@PC1 test2]# ls a.txt b.txt c.txt result.txt test.py x.csv y.csv [root@PC1 test2]# cat result.txt ## 合并结果 a a a b b b c c c d d d e e e f f f
2、合并csv文件
[root@PC1 test2]# ls a.txt b.txt test.py x.csv y.csv [root@PC1 test2]# cat a.txt a a a b b b [root@PC1 test2]# cat b.txt c c c d d d [root@PC1 test2]# cat x.csv 8 9 4 2 3 9 [root@PC1 test2]# cat y.csv 8 4 2 2 4 8 [root@PC1 test2]# cat test.py #!/usr/bin/python out_file = open("result.txt", "w") import os for i in os.listdir(): if i.endswith(".csv"): tmp_file = open(i, "r") for j in tmp_file: out_file.write(j) tmp_file.close() out_file.close() [root@PC1 test2]# python test.py [root@PC1 test2]# ls a.txt b.txt result.txt test.py x.csv y.csv [root@PC1 test2]# cat result.txt ## 合并结果 8 9 4 2 3 9 8 4 2 2 4 8
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2021-06-07 c语言 13-4
2021-06-07 c语言 13-3
2021-06-07 c语言 13-3
2021-06-07 c语言 13 - 3
2021-06-07 c语言中冒泡排序法