When I run this code in python 2.7, I get this error:
Traceback (most recent call last):
File \"C:\\Python26\\Lib\\site-packages\\pyutilib.subprocess-3.5.4\\
I solved it by treating file as a string, i.e. put "__file__"
(together with the quotes!) instead of __file__
This works fine for me:
wk_dir = os.path.dirname(os.path.realpath('__file__'))
If all you are looking for is to get your current working directory os.getcwd()
will give you the same thing as os.path.dirname(__file__)
as long as you have not changed the working directory elsewhere in your code. os.getcwd()
also works in interactive mode.
So
os.path.join(os.path.dirname(__file__))
becomes
os.path.join(os.getcwd())
change your codes as follows! it works for me. `
os.path.dirname(os.path.abspath("__file__"))
What you can do is to use the following
import os
if '__file__' in vars():
wk_dir = os.path.dirname(os.path.realpath('__file__'))
else:
print('We are running the script interactively')
Note here that using the string '__file__'
does indeed refer to the actual variable __file__
. You can test this out yourself of course..
The added bonus of this solution is the flexibilty when you are running a script partly interactively (e.g. to test/develop it), and can run it via the commandline
Are you using the interactive interpreter? You can use
sys.argv[0]
You should read: How do I get the path of the current executed file in Python?
I'm having exacty the same problem and using probably the same tutorial. The function definition:
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
is buggy, since os.path.dirname(__file__)
will not return what you need. Try replacing os.path.dirname(__file__)
with os.path.dirname(os.path.abspath(__file__))
:
def read(*rnames):
return open(os.path.join(os.path.dirname(os.path.abspath(__file__)), *rnames)).read()
I've just posted Andrew that the code snippet in current docs don't work, hopefully, it'll be corrected.