1

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.

2
  • It's not clear what you are trying to achieve. In your example Project Folder/filename.png do you want just Project Folder or /the/full/path/to/Project Folder/? Commented Apr 12, 2020 at 8:49
  • No its giving me the project folder for the code- as in where the code is. The png's are in a separate drive. So what its returning is artificial- as if the png's are in the same folder as the code, but they aren't. I just want the real path for each png. Commented Apr 12, 2020 at 8:53

3 Answers 3

1

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()])
Sign up to request clarification or add additional context in comments.

Comments

0

I just recently wrote something like what you're looking for.

This code relies on the assumption that your files are the end of the path. it's not suitable to find a directory or something like this.

there's no need for a nested loop.


DIR = "your/full/path/to/direcetory/containing/desired/files"

def get_file_path(name, template):
    """
    @:param template:  file's template (txt,html...)
    @return: The path to the given file.
    @rtype: str
    """
    substring = f'{name}.{template}'
    for path in os.listdir(DIR):
        full_path = os.path.join(DIR, path)
        if full_path.endswith(substring):
            return full_path

2 Comments

Hey Yovel, if the png's are in a subdirectory of DIR, is this going to give it a problem? At the moment its returning 'None'
then, your absolute path is DIR/pics_dir, Not DIR
0

The result from

for root, dirs, files in os.walk(newpath):

is that files just contains the filenames without a directory path. Using just filenames means that python by default uses your project folder as directory for those filenames. In your case the files are in newpath. You can use os.path.join to add a directory path to the found filenames.

filepath = os.path.join(newpath, file)

In case you want to find the png files in subdirectories the easiest way is to use glob:

import glob

newpath = r'D:\Images'


file_paths = glob.glob(newpath + "/**/*.png", recursive=True)

for file_path in file_paths:
    print(file_path)

2 Comments

Thats very close to being a solution, but the png's are in subdirectories of newpath. How do I find out which subdirectory they're in, so that I can join that to the filepath at the same time?
Finding files in subdirectories is easiest with glob. Like Alex's example or the way I do it. See the addition to my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.