我正在尝试合并文件夹中的所有文本文件。我的这部分工作正常,但是当我尝试在每个文本文件的内容之前附加文件名时,出现一条错误消息:TypeError: a bytes-like object is required, not 'str'
下面的代码必须非常接近,但是肯定存在问题。有什么想法可能是错的吗?
import glob
folder = 'C:\\my_path\\'
read_files = glob.glob(folder + "*.txt")
with open(folder + "final_result.txt", "wb") as outfile:
for f in read_files:
with open(f, "rb") as infile:
outfile.write(f)
outfile.write(infile.read())
outfile.close
outfile.write(f)
似乎是您的问题,因为您使用的二进制模式打开了文件'wb'
。您可以使用转换为字节。encode
您也可能不想outfile
在最后一行关闭(尽管无论如何您都不会调用该函数)。因此,这样的事情可能对您有用:
import glob
folder = 'C:\\my_path\\'
read_files = glob.glob(folder + "*.txt")
with open(folder + "final_result.txt", "wb") as outfile:
for f in read_files:
with open(f, "rb") as infile:
outfile.write(f.encode('utf-8'))
outfile.write(infile.read())
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句