【发布时间】:2014-11-04 09:32:39
【问题描述】:
在 Python 代码中处理多个文件时,使用推荐的样式可能会变得很难看:
with open("foo.txt") as foo:
with open("bar.txt", "w") as bar:
with open("baz.txt", "w") as baz:
# Read from foo, write different output to bar an baz
这只是用于处理文件的三个缩进级别!替代方案是这个
foo = open("foo.txt")
bar = open("bar.txt", "w")
baz = open("baz.txt", "w")
# Read from foo, write different output to bar an baz
foo.close()
bar.close()
baz.close()
我有一种感觉,这些示例中的任何一个都可以重构为更优雅的东西。有什么例子吗?
【问题讨论】:
-
with open('file1.txt') as f1, open('file2.txt') as f2:这样做。
标签: python file design-patterns refactoring