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