1

I'm a beginner working on my self project with some YouTube tutorial help. I came around this OS module, and I'm really confused what is the difference between

os.path.dirname(__file__)

and I've seen many of the experienced ones using:

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

does this really makes any difference? I've already seen some answers, either they are bit complex for me or I'm not satisfied with their explanation. Plz can anyone explain me in detail each's significance.

import os

p = os.path.dirname(os.path.abspath(__file__))
q = os.path.dirname(__file__)

Output:

C:\Users\ashud\Documents\Python Scripts
C:/Users/ashud/Documents/Python Scripts
Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
Hououin Kyouma
  • 163
  • 1
  • 2
  • 8
  • Related [1](https://stackoverflow.com/questions/3718657/how-to-properly-determine-current-script-directory) and [2](https://stackoverflow.com/questions/37863476/why-would-one-use-both-os-path-abspath-and-os-path-realpath) – Tony Tannous Sep 06 '19 at 16:37
  • If you're on Windows, symlinks are very rare and unusual, so you won't see the difference often. – Charles Duffy Sep 06 '19 at 16:41
  • However, if you were on an operating system where they were common, your `__file__` could be something like, say, `/home/yourname/.nix-profile/usr/lib/python-3.5/whatever/__init__.py`, and your `os.path.abspath(__file__)` could be something like `/nix/store/-whatever-Python35/usr/lib/python-3.5/whatever/__init__.py`, where the first is just the location of a link, and the second is where the file *really* lives. (That's a real-world-ish example for folks using Nix as their package manager). – Charles Duffy Sep 06 '19 at 16:44
  • not directly relevant, but note that python 3 has the `pathlib` library, which implements paths as objects and has a somewhat more readable API than `os.path`. – Eevee Sep 06 '19 at 18:04

0 Answers0