Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 876
SNTag Avatar asked Dec 21 '25 00:12

SNTag


1 Answers

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.

like image 89
Brad Solomon Avatar answered Dec 22 '25 13:12

Brad Solomon