frazman
frazman

Reputation: 33213

os.path.join(os.path.dirname(__file__)) returns nothing

I have a directory structure like this:

--bin/
--lib/
--data/

So basically, the executable script is in bin and it calls the files in lib.. but lib has to communicate with the text files in data

Usually this use to work: TO read a file in usually i use to do this

file_path =  os.path.join(os.path.dirname(__file__))+ "/../" +"data/"+filename
f = open(file_path,"r")

But, in this instance, if i do:

  print os.path.join(os.path.dirname(__file__))
  returns nothing?

What am i doing wrong.. Thanks

Upvotes: 1

Views: 10106

Answers (3)

mgilson
mgilson

Reputation: 309821

One other comment in addition to the others...the point of os.path.join is to avoid things like

mypath=dir + '/' + subdir + '/'+filename

This is done much more cleanly using

mypath=os.path.join(dir,subdir,filename) # can have as many arguments as you want!

Also, you can avoid explicit '..' and '.' in path names by using os.pardir and os.curdir. (e.g.)

file_path =  os.path.join(os.path.dirname(__file__),os.pardir,'data',filename)

This should increase the portability of your code (and is a good habit to get into even if you don't plan on running this script anywhere else).

Upvotes: 3

Amr
Amr

Reputation: 735

It depends on how you start your script, for example:

if /bin/script.py contains:

import os
print os.path.dirname(__file__)   #no reason to use os.path.join()

then:

$> python /bin/script.py
/bin
$> cd /bin
$> python script.py
                       #nothing
$>

It'a a better idea to use the following:

file_path = os.path.abspath(__file__)

and then do whatever you want with that.

Upvotes: 1

Michael
Michael

Reputation: 9058

I guess with nothing you mean an empty string? This could only be the case, if __file__ was an empty string in the first place. Did you accidentally overwrite __file__?

Upvotes: 4

Related Questions