Geo*_*off 10 python append with-statement
事实证明,"with"在互联网上搜索是一个有趣的词.
有谁知道在python中嵌套语句有什么用处?
我一直在追踪我写的剧本中一个非常滑的错误,我怀疑这是因为我这样做:
with open(file1) as fsock1:
with open(file2, 'a') as fsock2:
fstring1 = fsock1.read()
fstring2 = fsock2.read()
Run Code Online (Sandbox Code Playgroud)
当我尝试使用read()fsock2 时,Python会抛出.在调试器中检查时,这是因为它认为文件是空的.这不会令人担忧,除了在调试交互操作中运行完全相同的代码而不是在with语句中显示该文件实际上是非常充满文本的...
我将继续假设现在嵌套with语句是禁止的,但如果知道更多的人有不同的意见,我很乐意听到它.
rmi*_*ero 18
我在python的doc中找到了解决方案.你可能想看看这个
如果您正在运行python 3.1+,您可以像这样使用它:
with open(file1) as fsock1, open(file2, 'a') as fsock2:
fstring1 = fsock1.read()
fstring2 = fsock2.read()
Run Code Online (Sandbox Code Playgroud)
这样可以避免不必要的缩进.
在调试器中检查后,这是因为它认为文件为空。
我认为发生这种情况是因为它实际上无法读取任何内容。即使可能,将附加到文件时,查找指针也会移到文件末尾,以准备进行写操作。
这些with语句对我来说很好:
with open(file1) as f:
with open(file2, 'r') as g: # Read, not append.
fstring1 = f.read()
fstring2 = g.read()
Run Code Online (Sandbox Code Playgroud)
请注意contextlib.nested,如另一张海报所述,使用可能会在此处带来危险。假设您这样做:
with contextlib.nested(open(file1, "wt"), open(file2)) as (f_out, f_in):
...
Run Code Online (Sandbox Code Playgroud)
这里的上下文管理器一次创建一个。这意味着如果file2的打开失败(例如,因为它不存在),那么您将无法正确地完成file1的处理,而必须将其留给垃圾收集器处理。这可能是一件非常糟糕的事情。
| 归档时间: |
|
| 查看次数: |
7517 次 |
| 最近记录: |