NameError: name 'os' is not defined -- os.listdir error when printing all the files in a folder

StackOverflow https://stackoverflow.com/questions/21110734

  •  27-09-2022
  •  | 
  •  

문제

New to python and getting an error on this very simple script:

from os import listdir

all_files = os.listdir("/root/raw/")
for file in all_files:
    print file

What am I doing wrong here? Looks correct according to the docs.

도움이 되었습니까?

해결책

You have imported listdir from os so os.listdir means nothing, whereas listdir does mean something

Either call

all_files = listdir("/root/raw/")

Or change the import to

import os

다른 팁

You have imported only listdir function and that is in your current namespace. So you can directly access it, like this

all_files = listdir("/root/raw/")

If you had done,

import os

then you have imported the os module and to access listdir, you have to use os.listdir

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top