擅长:python、mysql、java
<p>据我所知,使用<code>fileinput</code>模块是没有办法解决这个问题的。您可以使用<code>codecs</code>模块、<code>os.rename()</code>和{<cd4>}组合完成相同的任务:</p>
<pre><code>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_name) # rename temp to original name
</code></pre>
<p>如果要更改输出文件,还可以选择为输出文件指定新的编码;如果不希望更改输出文件,则可以在打开输出文件时将其保留为<code>latin-1</code>。在</p>
<p>我知道这不是你想要的就地修改,但它可以完成你试图完成的任务,而且非常灵活。在</p>