Python OS.PATH:为什么要更改路径值?

Python OS.PATH:为什么要更改路径值?,python,os.path,Python,Os.path,我使用非常有用的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.ch

我使用非常有用的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

我不明白:

为什么目录文件的路径正在更改

我没有进入\目录的任何目录


感谢您的回答

如果您阅读了[abspath][1]函数的文档,您就会理解为什么会出现额外的目录

返回路径名路径的规范化绝对化版本。在大多数平台上,这相当于调用函数normpath,如下所示:normpathjoinos.getcwd,path

基本上,os.path.abspath'directory'为您提供当前目录中名为'directory'的内容的绝对路径,该目录也被称为'directory'

您看到的绝对路径是您刚刚创建的目录中的某些内容,这些内容还不存在。您创建的目录的绝对路径仍然保持不变,您可以通过以下方式进行检查:

os.path.abspath('.') # . -> current directory, is the one you created
abspath将文件名转换为相对于当前工作目录指定的文件名,但是,该文件不一定存在

因此,abpath的第一个调用:

# get the path of the directory
path = os.path.abspath("directory")
print(f"path after creating the directory: {path}")
只需将当前工作目录放在字符串目录的前面,您就可以轻松完成以下操作:

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

如果使用os.chdirectory更改工作目录,则os.getcwd将返回p:\Code\Python\directory,并将第二个\目录附加到路径。在这里您可以看到,文件不必存在。

您应该使用真实路径和完整路径。最后,os.path.abspath只创建了一个字符串,它不需要表示实际的目录结构。非常感谢。我得到它:os.path.abspath=>得到当前目录路径。如何获取文件或目录的绝对路径?非常感谢,如何获取文件或目录的绝对路径?您可以检查路径是否存在。但是对于路径操作,我个人更喜欢python的pathlib:非常感谢。我会的。祝你今天愉快