尝试用 pandas 子集替换open(),但是出现__exit__错误? [英] attempting to replace open() with a pandas subset, but I am given an __exit__ error?
问题描述
我正在尝试与pylabels一起为即将发生的事件创建名称标签.在代码的一部分中,有以下tid位:
I am trying to work with pylabels to create nametags for an upcoming event. In one section of the code, there is this tid-bit:
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"的每一行并使用"specs"中的规范调用函数"write_name",并将每个名称添加到唯一标签中.我正在尝试将此代码更改为以下代码:
where sheet = labels.Sheet(specs, write_name, border=True)
. So essentially, this will load each line of "names.txt" and call the function 'write_name', using specifications in 'specs', and add each name to unique labels. I'm attempting to change this code to the following:
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__
有人可以帮助我了解在这种情况下退出的含义吗?其他提交的内容我不明白.
Can anyone help me understand what exit means in this context? I do not understand from other submissions.
我希望添加此子集方面,以便我可以在名称标签中添加更多详细信息.
I am hoping to add this subsetting aspect so that I can add further details to the nametags.
我正在使用Python3.5
I am using Python3.5
推荐答案
有人可以帮助我了解
__exit__
在这种情况下的含义吗?我从其他意见中看不出来. ...text_file
不是函数,因此应该可以退出.
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
语句上下文管理器时,则该对象必须定义以下两种方法:
When you use with
statement context managers, that object must define these two methods:
-
__enter__
-
__exit__
__enter__
__exit__
无论text_file[["Name"]]
是什么(看起来是Pandas DataFrame),它都不会实现这两种方法.如回溯所示,它根本没有定义__enter__
,因此执行从此处停止并引发异常.
Whatever text_file[["Name"]]
is (a Pandas DataFrame, it seems), it doesn't implement either of these methods. As indicated by the traceback, it doesn't define __enter__
at all, so execution stops right there and raises an exception.
我认为不需要使用DataFrame作为上下文管理器.一个典型的用例是当您要确保在with
块的末尾发生某些事情时,即关闭文件流. (就像try
/finally
块一样-您想确保__exit__
被无条件调用.)对于Pandas DataFrame,我不确定是否有任何类比需要这两个dunder方法.
I don't see a need to use a DataFrame as a context manager. A typical use-case is when you want to ensure that something happens at the end of the with
block, namely, closing a file stream. (Like a try
/finally
block--you want to make sure __exit__
gets called unconditionally.) With a Pandas DataFrame, I'm not sure if there is any analogy that would necessitate have those two dunder methods.
这篇关于尝试用 pandas 子集替换open(),但是出现__exit__错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!