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
  •  | 
  •  

Pergunta

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.

Foi útil?

Solução

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

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top