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
复制代码

 

posted @   小鲨鱼2018  阅读(153)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!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语言中冒泡排序法
点击右上角即可分享
微信分享提示