简体   繁体   中英

Python OS.PATH : why abspath changing value?

I use the very usefull OS library for IT automation.

Bellow the code to create a folder / move into the folder / create a file

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

oupput:

path after creating the directory: P:\\Code\\Python\\directory

path after changing current directory: P:\\Code\\Python\\directory\\directory

I don't understand something:

Why the path of the directory file is changing?

I don't have any directory into \\directory

Thanks for your answers

If you read the documentation of the [abspath][1] function, you would understand why the extra directory is coming.

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)).

Basically, os.path.abspath('directory') is giving you "the absolute path of something named 'directory' inside the current directory (which also happens to be called 'directory') would be"

The absolute path you're seeing is for something inside the directory you just created, something that doesn't yet exist. The absolute path of the directory you created is stil unchanged, you can check that with:

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

os.path.abspath translates a the name of a file specified relative to your current working directory, however, the file does not necessarily exist.

So the first call of abpath:

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

does nothing more than putting your current working directory in front of the string "directory", you can easily do this by yourself:

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

If you change your working directory with os.chdir("directory") the os.getcwd() returns P:\\Code\\Python\\directory , and appends the second "\\directory" to the path. Here you see, that the file does not have to exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM