Python OS.PATH : 为什么 abspath 改变值?

Python OS.PATH : why abspath changing value?

我使用非常有用的 OS 库来实现 IT 自动化。

下面的代码创建一个文件夹/移动到文件夹/创建一个文件

import os

# create a directory
os.mkdir("directory")

# get the path of the directory
path = os.path.abspath("directory")
print(f"path after creating the directory: {path}")

# change current directory
os.chdir("directory")
path = os.path.abspath("directory")
print(f"path after changing current directory: {path}")

# create a file
with open("hello.py", "w"):
    pass

输出:

创建目录后的路径:P:\Code\Python\directory

更改当前目录后的路径:P:\Code\Python\directory\directory

我有点不明白:

为什么目录文件的路径在变化?

我在 \directory

中没有任何目录

感谢您的回答

如果你阅读了 [abspath][1] 函数的文档,你就会明白为什么会出现额外的 directory

Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).

基本上,os.path.abspath('directory') 给你 "the absolute path of something named 'directory' inside the current directory (which also happens to be called 'directory') would be"

您看到的绝对路径是针对您刚创建的目录中的某些内容,某些内容尚不存在。您创建的目录的绝对路径仍然没有改变,您可以通过以下方式检查:

os.path.abspath('.') # . -> current directory, is the one you created

os.path.abspath 翻译一个相对于当前工作目录指定的文件名,但是,该文件不一定存在。

所以abpath的第一次调用:

# get the path of the directory
path = os.path.abspath("directory")
print(f"path after creating the directory: {path}")

无非是把你当前的工作目录放在字符串"directory"的前面,你可以自己轻松做到:

os.getcwd() + '/' + "directory"

如果您使用 os.chdir("directory") os.getcwd() returns P:\Code\Python\directory 更改您的工作目录,并将第二个 "\directory" 附加到路径。在这里您可以看到,该文件不一定存在。