问题
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. ... Astext_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