【问题标题】:Python "with os.chdir('/opt/intel/mkl/bin'): AttributeError: __enter__" ErrorPython "with os.chdir('/opt/intel/mkl/bin'): AttributeError: __enter__" 错误
【发布时间】:2020-09-12 08:05:24
【问题描述】:

我正在尝试去“/opt/intel/mkl/bin”并列出文件并检查一些文件的存在并出来。我收到此错误。任何帮助表示赞赏。

files = ['mklvars.csh','mklvars.sh']
with os.chdir('/opt/intel/mkl/bin'):
    print('testing')
    if all([os.path.isfile(f)for f in files]):
        print("Installation succesful")
    else:
        print("not succesful")```

【问题讨论】:

  • 帮助我们帮助你 - 分享完整的追溯
  • @Mureinik 当然,Traceback (most recent call last): File "py.py", line 3, in <module> with os.chdir('/opt/intel/mkl/bin'): AttributeError: __enter__

标签: python-3.x


【解决方案1】:

您只能将关键字with ... : 与上下文管理器一起使用,而os.chdir() 不是上下文管理器。

您可以简单地执行类似的操作(如果您之后不需要恢复工作目录)

files = ['mklvars.csh','mklvars.sh']
os.chdir('/opt/intel/mkl/bin')
print('testing')
if all([os.path.isfile(f) for f in files]):
    print("Installation succesful")
else:
    print("not succesful")

但如果您需要在最后恢复当前工作目录,您可以使用不同的选项。

一个例子(https://github.com/jaraco/path):

from path import Path

# Changing the working directory:
files = ['mklvars.csh','mklvars.sh']
with Path('/opt/intel/mkl/bin'):
    print('testing')
    if all([os.path.isfile(f)for f in files]):
        print("Installation succesful")
    else:
        print("not succesful")

其他解决方案:checkout this Question

进一步阅读上下文管理器:

【讨论】:

    猜你喜欢
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    • 2019-12-01
    • 2018-05-27
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多