pythonoperating-systempython-oslistdir

name 'listdir' is not defined


I have been trying to run this cell on google colab but every time it says 'listdir' is not defined. I have imported 'os' in the previous cell before running this cell. Can anyone please help to find the error here?

images =  [(train_image_dir+f) for f in listdir(train_image_dir) if isfile(join(train_image_dir, f))]

Solution

  • Instead of calling listdir(), call os.listdir(). A bit unclear what you're trying to accomplish from your indentation but you need to indicate the package from which all of these functions are from, unless you specifically import each function. As state above by @E.Serra, either of these options will work:

    from os import listdir
    from os.path import join, isfile
    

    or:

    import os
    
    # later in code...
    os.listdir(directory)
    os.path.join("string1", "string2")
    os.isfile(file)