1

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

frazman
  • 32,081
  • 75
  • 184
  • 269

3 Answers3

4

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__?

Michael
  • 8,920
  • 3
  • 38
  • 56
  • I am not sure, I quite understand... (sorry.. still learning all this).. there are two files, file1.py over there I am reading a file.. and it works.. and then in file2.py (which is read after file1.py) and i do this same thing.. but it returns empty string – frazman Jun 08 '12 at 17:44
  • hey.. thanks.. it works.. my bad.. I was doing this. filepath = os.path.join(os.path.dirname(__file__))+ "/../" +"data/"+filename So it was returning a null.. as file name and then +"/.." means going cding to null i think :) thanks – frazman Jun 08 '12 at 17:47
3

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).

mgilson
  • 300,191
  • 65
  • 633
  • 696
1

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.

Amr
  • 695
  • 4
  • 11