好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python批量合并多个txt文件

 # -*- coding:utf-8 -*-  
  
#os模块中包含很多操作文件和目录的函数  
import os  
#获取目标文件夹的路径  
meragefiledir = os.getcwd()+'\\MerageFiles'
#获取当前文件夹中的文件名称列表  
filenames=os.listdir(meragefiledir)  
#打开当前目录下的result.txt文件,如果没有则创建
file=open('result.txt','w', encoding='utf8')  
#向文件中写入字符  
  
#先遍历文件名  
for filename in filenames:  
    filepath=meragefiledir+'\\'
    filepath=filepath+filename
    #遍历单个文件,读取行数  
    for line in open(filepath, encoding='utf8'):  
        file.writelines(line)  
    file.write('\n')  
#关闭文件  
file.close()  
 

问题

1, UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 2: illegal multibyte sequence windows打开文件默认是以==“gbk“编码的,可能造成不识别unicode==字符,于是做了如下的修改:

 self.file = open('biaobai.json', 'w', encoding="utf-8")
self.file.write(content)
 

参考

1,Python 批量合并多个txt文件https://blog.csdn.net/LINZHENYU1996/article/details/77972762 2,UnicodeEncodeError: ‘gbk’ codec can’t encode character https://HdhCmsTestcnblogs测试数据/cwp-bg/p/7835434.html

查看更多关于Python批量合并多个txt文件的详细内容...

  阅读:38次