我正在尝试使用下面的代码搜索和替换多个 html 文件中的文本,它适用于 .txt,而不适用于转换为 .txt 的 html。 是utf-16的问题吗?我怎样才能让它发挥作用?
import os
directory ="/Users/sinanatra/PYTHON_STUFF/MSN/0/"
replacement = "test"
for dname, dirs, files in os.walk(directory):
for fname in files:
fpath = os.path.join(dname, fname)
with open(fpath) as f:
s = f.read()
s = s.replace("head", replacement)
with open(fpath, "w") as f:
f.write(s)
最佳答案
如果你使用utf-16那么你需要
s.read().decode('utf-16')
对于写入,您将需要:
f.write(s.encode('utf16'))
关于python - 使用 python 搜索/替换 html 文件中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44084650/