EEEEH
EEEEH

Reputation: 779

How to explain os.path.abspath(__file__ + "/..")?

As title

import os

print(os.path.abspath(__file__))
print(os.path.abspath(__file__ + "/.."))

Output:

/Users/myname/my_proj/__init__.py
/Users/myname/my_proj

I want to know _file_+"/.." meaning exactly.

Upvotes: 0

Views: 512

Answers (2)

rzlvmp
rzlvmp

Reputation: 9364

I want to know file+"/.." meaning exactly.

meaning

A ".." can also be used in a command line or in a file path to go back one directory. For example, when using either the MS-DOS cd command or Linux and Unix cd command typing cd .. goes back one directory.

In other words

  • /home/user/../ (or /home/user/..) same as /home
  • /home/user/../anotheruser same as /home/anotheruser
  • /home/user/./ (or /home/user/.) same as /home/user
  • /home/user/./anotheruser same as /home/user/anotheruser

However, that is interesting question. This hack don't work for Linux commands:

ls -l /var/log/system.log
-rw-r-----@ 1 root  root  165030 Jan 27 13:18 /var/log/system.log

ls -l /var/log/system.log/..
ls: /var/log/system.log/..: Not a directory

But! python abspath library ignores is the last element of path folder or directory

Upvotes: 2

Barmar
Barmar

Reputation: 781058

Use os.path.dirname()

print(os.path.abspath(os.path.dirname(__file__)))

Upvotes: 3

Related Questions