【问题标题】:Can't get absolute path in Python无法在 Python 中获取绝对路径
【发布时间】:2020-04-12 08:17:28
【问题描述】:

我尝试使用os.path.abspath(file)Path.absolute(file) 来获取我正在处理的.png 文件的路径,这些文件位于与代码所在的项目文件夹不同的驱动器上。结果来自以下脚本的是“代码/文件名.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)

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

【问题讨论】:

  • 不清楚您要达到的目标。在您的示例Project Folder/filename.png 中,您想要Project Folder 还是/the/full/path/to/Project Folder/
  • 不,它给了我代码的项目文件夹-就像代码所在的位置一样。 png 位于单独的驱动器中。所以它的返回是人为的——好像 png 和代码在同一个文件夹中,但它们不是。我只想要每个 png 的真实路径。

标签: python filepath os.path pathlib


【解决方案1】:

您可以在这里使用pathlib.Path.rglob 递归获取所有的png:

作为列表理解:

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")]

或者,您可以循环处理它们:

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

【讨论】:

    【解决方案2】:

    我最近刚刚写了一些你正在寻找的东西。

    此代码依赖于您的文件位于路径末尾的假设。 不适合找目录之类的。

    不需要嵌套循环。

    
    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
    

    【讨论】:

    • 嘿,Yovel,如果 png 位于 DIR 的子目录中,这会给它带来问题吗?目前它返回“无”
    • 那么,你的绝对路径是DIR/pics_dir,不是DIR
    【解决方案3】:

    结果

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

    files 只包含文件名,没有目录路径。 仅使用文件名意味着 python 默认使用您的项目文件夹作为这些文件名的目录。在您的情况下,文件位于新路径中。您可以使用 os.path.join 为找到的文件名添加目录路径。

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

    如果您想在子目录中查找 png 文件,最简单的方法是使用 glob:

    import glob
    
    newpath = r'D:\Images'
    
    
    file_paths = glob.glob(newpath + "/**/*.png", recursive=True)
    
    for file_path in file_paths:
        print(file_path)
    

    【讨论】:

    • 这非常接近解决方案,但 png 位于 newpath 的子目录中。如何找出它们所在的子目录,以便同时将其加入文件路径?
    • 使用 glob 最容易在子目录中查找文件。就像亚历克斯的例子或我这样做的方式。请参阅我的答案的补充内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2015-04-14
    • 2010-09-08
    • 1970-01-01
    • 2012-09-03
    相关资源
    最近更新 更多