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

Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top