打开文件,读取,处理和回写 - Python中的最短方法

Eli*_*sky 13 python coding-style

我想对文件做一些基本的过滤.读它,做处理,写回来.

我不是在寻找"打高尔夫球",而是想要最简单,最优雅的方法来实现这一目标.我提出了:

from __future__ import with_statement

filename = "..." # or sys.argv...

with open(filename) as f:
    new_txt = # ...some translation of f.read() 

open(filename, 'w').write(new_txt)
Run Code Online (Sandbox Code Playgroud)

with语句使事情更短,因为我不必显式打开和关闭文件.

还有其他想法吗?

Hor*_*ude 26

实际上使用fileinput更简单的方法是使用inplace参数:

import fileinput
for line in fileinput.input (filenameToProcess, inplace=1):
    process (line)
Run Code Online (Sandbox Code Playgroud)

如果使用inplace参数,它会将stdout重定向到您的文件,因此如果您执行打印,它将回写到您的文件.

此示例为您的文件添加行号:

import fileinput

for line in fileinput.input ("b.txt",inplace=1):
    print "%d: %s" % (fileinput.lineno(),line),
Run Code Online (Sandbox Code Playgroud)