TheRealFakeNews
TheRealFakeNews

Reputation: 8183

Python: How to obtain directory of current script being run?

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.

Upvotes: 1

Views: 296

Answers (1)

Amadan
Amadan

Reputation: 198486

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.

Upvotes: 4

Related Questions