Search code examples
pythonfilepathos.pathpathlib

Can't get absolute path in Python


I've tried to use os.path.abspath(file) as well as Path.absolute(file) to get the paths of .png files I'm working on that are on a separate drive from the project folder that the code is in. The result from the following script is "Project Folder for the code/filename.png", whereas obviously what I need is the path to the folder that the .png is in;

for root, dirs, files in os.walk(newpath):
    for file in files:
        if not file.startswith("."):
            if file.endswith(".png"):
                number, scansize, letter = file.split("-")
                filepath = os.path.abspath(file)
                # replace weird backslash effects
                correctedpath = filepath.replace(os.sep, "/")
                newentry = [number, file, correctedpath]
                textures.append(newentry)

I've read other answers on here that seem to suggest that the project file for the code can't be in the same directory as the folder that is being worked on. But that isn't the case here. Can someone kindly point out what I'm not getting? I need the absolute path because the purpose of the program will be to write the paths for the files into text files.


Solution

  • You could use pathlib.Path.rglob here to recursively get all the pngs:

    As a list comprehension:

    from pathlib import Path
    search_dir = "/path/to/search/dir"
    # This creates a list of tuples with `number` and the resolved path
    paths = [(p.name.split("-")[0], p.resolve()) for p in Path(search_dir).rglob("*.png")]
    

    Alternatively, you can process them in a loop:

    paths = []
    for p in Path(search_dir).rglob("*.png"):
        number, scansize, letter = p.name.split("-")
        # more processing ...
        paths.append([number, p.resolve()])