Python合并txt文件报TypeError: can only concatenate str (not "bytes") to str怎么解决
问题修复方案
错误原因
你打开读写文件时用了rb/wb二进制模式,这种模式下读取到的内容Line是bytes字节类型,而你拼接的str(i+1)+" "是字符串类型,两类数据不能直接拼接,所以触发类型错误。
修复方案
提供两种常用修复思路,按需选择即可:
方案1:统一使用文本模式读写(更适合纯文本txt场景)
把打开文件的rb改成r、wb改成w,全流程用字符串处理,不需要额外转码:
import glob read_files = [] file_name = 'img/img' for i in range(1,14912): read_files.append(file_name+str(i)+".txt") with open("result.txt","w", encoding="utf-8") as outfile: for i,f in enumerate(read_files): with open(f, "r", encoding="utf-8") as infile: Lines = infile.readlines() for Line in Lines: outfile.write(str(i+1)+" "+Line)
建议显式指定encoding参数避免不同系统默认编码不一致导致乱码
方案2:保持二进制模式,把拼接后的字符串转成bytes再写入
如果确实需要用二进制模式读写,把你要写入的前缀字符串转成bytes类型再和Line拼接:
import glob read_files = [] file_name = 'img/img' for i in range(1,14912): read_files.append(file_name+str(i)+".txt") with open("result.txt","wb") as outfile: for i,f in enumerate(read_files): with open(f, "rb") as infile: Lines = infile.readlines() for Line in Lines: # 把字符串转成utf-8编码的bytes再拼接 outfile.write((str(i+1)+" ").encode('utf-8') + Line)
内容的提问来源于stack exchange,提问作者hrithik mahesh
相关产品推荐
相关产品推荐

