无法在Python中获得绝对路径

问题描述 投票:0回答:1

我尝试使用os.path.abspath(file)以及Path.absolute(file)来获取我正在处理的.png文件的路径,该路径位于与项目文件夹不同的驱动器上代码在其中。以下脚本的结果是“ Project Folder / filename.png”,而显然我需要的是.png所在文件夹的路径;

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)

我已经在这里阅读了其他答案,似乎表明该代码的项目文件不能与正在处理的文件夹位于同一目录中。但这不是事实。有人可以指出我没有得到什么吗?我需要绝对路径,因为该程序的目的是将文件的路径写入文本文件。

非常感谢

python filepath os.path pathlib
1个回答
0
投票

我最近刚刚写了一些您想要的东西。

此代码基于以下假设:您的文件位于路径的末尾。不适合查找目录或类似内容。

不需要嵌套循环。


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

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
© www.soinside.com 2019 - 2024. All rights reserved.