python - 试图用 pandas 子集替换 open(),但出现 __exit__ 错误?

标签 python python-3.x pandas contextmanager

我正在尝试使用 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. ... As text_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/

相关文章:

python - 使 python 包表现为 native cli 应用程序

python - 为什么 python 整数缓存范围 [-5, 256] 不能在所有平台上以类似的方式工作?

python Pandas : Take Rows in my Column and categorize it as 1 Row?

python - 在 Python 中使用正则表达式删除数据框的部分列名

python - 如何使用 key 加密字符串

python - 使用脚本或正则表达式将 "printf"添加到每个函数

python - Jupyter Notebook 中的 Bokeh 图未更新

python - 如何使用 pandas 替换所有列中的所有字符串?

python-3.x - Selenium 和异步

python - 根据另一列中的组和条件填充列