我试图使用fileinput模块的就地过滤功能来就地重写输入文件。
需要将编码(用于读取和写入)设置为latin-1,并尝试将openhook=fileinput.hook_encoded('latin-1')传递给fileinput.input,但由于错误而受阻
ValueError: FileInput cannot use an opening hook in inplace mode
仔细检查后,我发现fileinput文档明确声明了这一点:您不能同时使用inplace和openhook
我该如何解决?
据我所知,fileinput模块无法解决此问题。您可以结合使用codecs模块,os.rename()和os.remove()来完成相同的任务:
import os
import codecs
input_name = 'some_file.txt'
tmp_name = 'tmp.txt'
with codecs.open(input_name, 'r', encoding='latin-1') as fi, \
codecs.open(tmp_name, 'w', encoding='latin-1') as fo:
for line in fi:
new_line = do_processing(line) # do your line processing here
fo.write(new_line)
os.remove(input_name) # remove original
os.rename(tmp_name, input