Qual é a diferença entre os.path.dirname(os.path.abspath(__file__)) e os.path.abspath(os.path.dirname(__file__))

Asked

Viewed 502 times

0

The two seem to return exactly the same. Inclusive, os.path.dirname(__file__) returns the same too.

1 answer

1

The way you are doing operations, the result has to be identical even. The function os.path.dirname('file') returns the name of the directory where the file is, but this name may be relative. For example, if the file is in the current directory, this function will return an empty string.

On the other hand, the function os.path.abspath('file') return the name absolute directory. That is, the name you effectively use to save and open files.

For example, if I need to save a dataframe to a csv file in my current directory, I should do:

df.to_csv(os.path.abspath('file.csv'))

But I couldn’t do:

df.to_csv(os.path.dirname('file.csv'))

Now, when you ask the program to do os.path.dirname(os.path.abspath('file')), You’re telling him, what’s the name of the absolute directory that file’s in? Since the name is absolute, there is no possibility for the dirname to return the relative name. On the other hand, when you do os.path.abspath(os.path.dirname('file')), you will have as output the absolute name of the directory, even if the name of the dirname function is the relative name.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.