python - 打开文件,读取它,处理,然后写回 - Python 中最短的方法

标签 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)

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

还有其他想法吗?

最佳答案

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

import fileinput
for line in fileinput.input (filenameToProcess, inplace=1):
    process (line)

如果您使用 inplace 参数,它会将 stdout 重定向到您的文件,这样如果您进行打印,它就会写回您的文件。

此示例将行号添加到您的文件中:

import fileinput

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

关于python - 打开文件,读取它,处理,然后写回 - Python 中最短的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/227461/

相关文章:

python - 将两个列表压缩到文本文件中

python - 导入错误 : DLL load failed(import h5py)

mysql - 创建大型 SQL 表的最佳实践

javascript - Jquery-代码优化

python - 为什么现在还有 "commands out of sync; you can' t run this command”错误

python - 未绑定(bind)本地错误: local variable 'region' referenced before assignment

java - 在 Java 中创建这样的 _fields_ 名称有什么问题?

java - Java 中的显式成员方法引用

python - 使用 Jinja2 和 Babel,如何翻译包含 HTML 标签的句子?

java - 重置计数器或让它增加并使用模数是否更有效