我正在尝试使用 pylabels 为即将举行的事件创建名称标签。在代码的一部分中,有这个花絮:
with open(os.path.join(base_path, "names.txt")) as names:
sheet.add_labels(name.strip() for name in names)
其中 sheet = labels.Sheet(specs, write_name, border=True)
。所以本质上,这将加载“names.txt”的每一行并调用函数“write_name”,使用“specs”中的规范,并将每个名称添加到唯一标签。我正在尝试将此代码更改为以下内容:
with text_file[["Name"]] as names:
sheet.add_labels(name.strip() for name in names)
但是我得到这个错误:
Traceback (most recent call last):
File "sticker.V.7.py", line 173, in <module>
with text_file[["Name"]] as names:
AttributeError: __exit__
任何人都可以帮助我理解 exit 在这种情况下的含义吗?我不明白其他提交的内容。
我希望添加这个子集方面,以便我可以向名称标签添加更多详细信息。
我使用的是Python3.5
最佳答案
Can anyone help me understand what
__exit__
means in this context? I do not understand from other submissions. ... Astext_file
isn't a function, it should be exitable.
当您使用 with
statement context managers 时,该对象必须定义这两个方法:
__enter__
__exit__
无论 text_file[["Name"]]
是什么(看起来是 Pandas DataFrame),它都没有实现这些方法中的任何一个。如回溯所示,它根本没有定义 __enter__
,因此执行就在那里停止并引发异常。
我认为不需要使用 DataFrame 作为上下文管理器。一个典型的用例是当您想要确保在 with
block 的末尾发生某些事情时,即关闭文件流。 (就像 try
/finally
block ——你要确保 __exit__
被无条件调用。)使用 Pandas DataFrame,我不是确定是否有任何类比需要使用这两种 dunder 方法。
关于python - 试图用 pandas 子集替换 open(),但出现 __exit__ 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53312256/