python合并多个txt文件

python合并多个txt文件

 
#合并一个文件夹下的多个txt文件
#coding=utf-8
import os
#获取目标文件夹的路径
filedir = os.getcwd()+'\数据'
#获取当前文件夹中的文件名称列表
filenames=os.listdir(filedir)
#打开当前目录下的result.txt文件,如果没有则创建
f=open('result.txt','w')
i=0
#先遍历文件名
for filename in filenames:
    i+=1
    print(i)
    if i>0:
        filepath = filedir+'\'+filename
        print(filepath)
        #遍历单个文件,读取行数
        for line in open(filepath,encoding='gbk', errors='ignore'):
            # print(str(line))
            f.writelines(line)
            # f.write('
')
#关闭文件
f.close()

  

欢迎光临程序代写小店https://item.taobao.com/item.htm?spm=a230r.1.14.59.255028c3ALNkZ0&id=586797758241&ns=1&abbucket=15#detail

可直接联系客服QQ交代需求:953586085

原文地址:https://www.cnblogs.com/chenbocheng/p/10839262.html