Search code examples
pythonpython-3.xpathlib

Finding the realpath of a file in unix


I have the following code, which is expected to do the following,

  • Directory name (dirName) and a prefix is provided as input to the function.
  • Lists out all the contents one level down from the provided input directory (dirName) and starts populating the file details within the sub directories using the os.walk function.
  • Once the files are found they are checked against a specific prefix and processed further.
  • The motive is that once a file is identified (which satisfies a prefix), I want the absolute realpath of that file. I tried using the Path(libfile).resolve() option but its giving only the present working directory from where the script is run as against the realpath of that file. Could you explain where I am going wrong?

    import os
    from pathlib import Path
    
    def directory(dirName, prefix):
    
    process_dir = [name for name in os.listdir(dirName) if os.path.isdir(os.path.join(dirName, name))]
    for entry in process_dir:
        for dirname, directory, files in os.walk(os.path.join(dirName, entry)):
            for libfile in files:
                if libfile.startswith((prefix)):
                    return(Path(libfile).resolve())
    

Python version 3.6.2.


Solution

  • Change this line:

    return(Path(libfile).resolve())
    

    To this:

    return (Path(dirname) / libfile).resolve()
    

    I agree with the comment from dawg that using a recursive glob pattern would be a better choice here.