1

In this post, the top answer explains how to (1) obtain the directory of the script being run, and (2) obtain the path of the working directory. However, I'm confused on the usage of __file__. BryanOakley even states to notice the double underscore of __file__, but I do not understand why. Essentially, what I am asking is if I wanted to use his snippet of code, how would I implement it?

I tried entering gibberish, such as 'lkajfoiwhjnafd;klj.txt' in leiu of __file__, and it still returned a path, even though I am certain no such file exists.

Cœur
  • 37,241
  • 25
  • 195
  • 267
TheRealFakeNews
  • 7,512
  • 16
  • 73
  • 114
  • `abspath` returns the absolute path of the file ... it does not care if the file exists or not `__file__` is the file for the current script ... – Joran Beasley Sep 18 '15 at 01:13
  • @JoranBeasley. That's not quite true: abspath may access the filesystem via `os.getcwd()`, and this can throw an error if the current directory doesn't exist. – ekhumoro Sep 18 '15 at 02:06
  • is it possible for the current cwd to not exist? – Joran Beasley Sep 18 '15 at 04:30
  • @JoranBeasley. Yes: change to a directory, then rename/delete it. Not sure whether the behaviour is the same on all platforms, but on linux `os.getcwd()` will then raise `FileNotFoundError`. – ekhumoro Sep 18 '15 at 15:25
  • in windows i dont think it will allow you to delete a directory that you are currently in ... so you are saying something like `cd /some/path;rm -rf .`? and that works in linux? – Joran Beasley Sep 18 '15 at 15:27

1 Answers1

4

He notes there are two underscores because on most fonts there is no break between adjacent underscores, and it might not have been obvious to the readers.

__file__ is the path to the current script. It is just magically there.

dirname and most other such functions operate on the path string, without actually accessing the file system.

Amadan
  • 191,408
  • 23
  • 240
  • 301