Search code examples
pythonlinuxpython-2.xwlst

Why am I getting an error importing os.walk in python2.7


I need to recursively search directories/subdirectories on a Linux server for directories of specific names and retrieve the files within those specific directories. I have tried 2 approaches, one where I import os and call os.walk and another where I import walk from os. Code below:

def getDeployedLibraries():
        serverConfig()
        path = 'somePath'
        deployments = cmo.getLibraries()
        print(divider)
        print("Library Deployments:" )
        print(divider)
        if deployments:
                deployedLibs = []
                stagedLibs = []
                archiveLibs = []
                for dep in deployments:
                        full_name = dep.getName()
                        path = dep.getAbsoluteSourcePath()
                        deployedLibs.append(path+full_name)
                for (dirpath, dirnames, files) in os.walk(path):
                        for name in dirnames:
                                if name != "shared-lib":
                                        dirnames.remove(name)
                        for file in files:
                                stagedLibs.append(file)
                for sLib in stagedLibs:
                        if sLib not in deployedLibs:
                                archiveLibs.append(sLib)
                f = open("filesToArchive.txt","w")
                f.write("\n".join(archiveLibs))
                f.close()
        else:
                deploymentsList.append("No deployments of this type installed.")
        domainConfig()
        return deploymentsList 

When just importing os and calling os.walk I get the error that AttributeError: class 'org.python.modules.os' has no attribute 'walk' and when I import walk from os and just call os, I get the error 'ImportError: cannot import name walk'.

This script does connect to WLST so I thought that maybe I was getting a conflict but didn't find anything to indicate such.


Solution

  • The function should be imported from os.path:

    from os.path import walk