attempting to replace open() with a pandas subset, but I am given an __exit__ error?

独自空忆成欢 提交于 2019-12-10 18:27:37

问题


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)

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)

But I get this error:

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.

I am using Python3.5


回答1:


Can anyone help me understand what __exit__ means in this context? I do not understand from other submissions. ... As text_file isn't a function, it should be exitable.

When you use with statement context managers, that object must define these two methods:

  • __enter__
  • __exit__

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.

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.



来源:https://stackoverflow.com/questions/53312256/attempting-to-replace-open-with-a-pandas-subset-but-i-am-given-an-exit-er

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!