NameError: the name "os" is not defined - the os.listdir error occurred while printing all files in the folder

New to python and getting errors in 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? It looks correct in accordance with the documents.

+3
source share
2 answers

You imported listdirfrom os, so os.listdirit means nothing, while it listdirmeans something

Call

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

Or change the import to

import os
+4
source

You only imported the function listdirthat is in your current namespace. This way you can directly access it, for example,

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

If you did this,

import os

os listdir, os.listdir

+3