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 @ 2022-06-07 20:40  小鲨鱼2018  阅读(145)  评论(0编辑  收藏  举报