2016-12-30 46 views
5

當我使用python文檔(here)中的示例代碼時引發了AttributeError。示例代碼如下:與os.scandir()引發AttributeError:__exit__

with os.scandir(path) as it: 
    for entry in it: 
     if not entry.name.startswith('.') and entry.is_file(): 
      print(entry.name) 

結果是AttributeError

D:\Programming>test.py 
Traceback (most recent call last): 
    File "D:\Programming\test.py", line 3, in <module> 
    with os.scandir() as it: 
AttributeError: __exit__ 

雖然,分配os.scandir()到可變工作正常。 有人能告訴我我錯過了什麼嗎?

回答

4

上下文管理器支持加入的Python 3.6,嘗試使用它與以前的版本將提高你看到的錯誤,因爲它不是一個上下文管理器(和Python試圖加載__exit__第一)。

This is stated in its documentation右下代碼片段,你所看到的)爲scandir

New in version 3.6: Added support for the context manager protocol and the close() method. [...]

(重點煤礦)

您可以更新到Python 3.6,或者,如果你不能,請勿將其用作上下文管理器。

2

文檔說

New in version 3.6: Added support for the context manager protocol

您可能正在運行舊版本的Python。

+0

就是這樣。我仍然在3.5.2.3.6完美的作品,謝謝! –

相關問題