对python os.path.abspath的误解

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24705679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:02:01  来源:igfitidea点击:

Misunderstanding of python os.path.abspath

pythonpathos.path

提问by Most Wanted

I have following code:

我有以下代码:

directory = r'D:\images'
for file in os.listdir(directory):
    print(os.path.abspath(file))

and I want next output:

我想要下一个输出:

  • D:\images\img1.jpg
  • D:\images\img2.jpg and so on
  • D:\图像\img1.jpg
  • D:\images\img2.jpg 等

But I get different result:

但我得到不同的结果:

  • D:\code\img1.jpg
  • D:\code\img2.jpg
  • D:\code\img1.jpg
  • D:\code\img2.jpg

where D:\code is my current working directory and this result is the same as

其中 D:\code 是我当前的工作目录,此结果与

os.path.normpath(os.path.join(os.getcwd(), file))

So, the question is: What is the purpose of os.path.abspath while I must use

所以,问题是: os.path.abspath 的目的是什么,而我必须使用

os.path.normpath(os.path.join(directory, file))

to get REAL absolute path of my file? Show real use-cases if possible.

获取我的文件的真正绝对路径?如果可能,展示真实的用例。

采纳答案by unholysampler

The problem is with your understanding of os.listdir()not os.path.abspath(). os.listdir()returns the names of each of the files in the directory. This will give you:

问题在于你对os.listdir()not的理解os.path.abspath()os.listdir()返回目录中每个文件的名称。这会给你:

img1.jpg
img2.jpg
...

When you pass these to os.path.abspath(), they are seen as relative paths. This means it is relative to the directory from where you are executing your code. This is why you get "D:\code\img1.jpg".

当您将这些传递给 时os.path.abspath(),它们被视为相对路径。这意味着它相对于您执行代码的目录。这就是你得到“D:\code\img1.jpg”的原因。

Instead, what you want to do is join the file names with the directory path you are listing.

相反,您要做的是将文件名与您列出的目录路径连接起来。

os.path.abspath(os.path.join(directory, file))

回答by chepner

listdirproduces the file names ina directory, with no reference to the name of the directory itself. Without any other information, abspathcan only form an absolute path from the only directory it can know about: the current working directory. You can always change the working directory before your loop:

listdir目录中生成文件名,不引用目录本身的名称。没有任何其他信息,abspath只能从它唯一知道的目录形成一个绝对路径:当前工作目录。您始终可以在循环之前更改工作目录:

os.chdir(directory)
for f in os.listdir('.'):
    print(os.path.abspath(f))

回答by Jonathan Eunice

Python's native os.listdirand os.pathfunctions are pretty low-level. Iterating through a directory (or a series of descending directories) requires your program to assemble file paths manually. It can be convenient to define a utility function that generates the paths you're going to need just once, so that path assembly logic doesn't have to be repeated in every directory iteration. For example:

Python 的本机os.listdiros.path函数非常低级。遍历一个目录(或一系列降序目录)需要您的程序手动组装文件路径。定义一个实用程序函数会很方便,该函数只生成一次您需要的路径,这样就不必在每次目录迭代中重复路径组装逻辑。例如:

import os

def better_listdir(dirpath):
    """
    Generator yielding (filename, filepath) tuples for every
    file in the given directory path.
    """
    # First clean up dirpath to absolutize relative paths and
    # symbolic path names (e.g. `.`, `..`, and `~`)
    dirpath = os.path.abspath(os.path.expanduser(dirpath))

    # List out (filename, filepath) tuples
    for filename in os.listdir(dirpath):
        yield (filename, os.path.join(dirpath, filename))

if __name__ == '__main__':
    for fname, fpath in better_listdir('~'):
        print fname, '->', fpath

Alternatively, there are "higher level" path modules that one can employ, such as py.path, path.py, and pathlib(now a standard part of Python, for version 3.4 and above, but available for 2.7 forward). Those add dependencies to your project, but up-level many aspects of file, filename, and filepath handling.

或者,可以使用“更高级别”的路径模块,例如py.pathpath.pypathlib(现在是 Python 的标准部分,适用于 3.4 及更高版本,但可用于 2.7 向前)。这些会为您的项目添加依赖项,但会提升文件、文件名和文件路径处理的许多方面。