Search code examples
pythonpathpydevabsolute-path

Absolute path in python


I'm writing a python project in eclipse with PyDev. And I'm facing a problem. Here's construction of project Here's construction of project

In a file in breaking_cipher package, I get the absolute path of "english_quadgrams.txt"

def __init__(self,filename="./dic/english_quadgrams.txt"):
    self.filename = os.path.abspath(filename)
    #self.filename = filename
    print "self:", self.filename
    self.dic,self.floor = generate_dic(self.filename)

The issue is when I import project to use in comandline, it obtained wrong abs dir. The dir shoudbe be "C:\Users\windy_000\workspace\cipher\dic\english_quadgrams.txt", but error display "C:\Users\windy_000\workspace\dic\english_quadgrams.txt". comandline Did I do something wrong?


Solution

  • Relative path is relative to the current working directory (os.getcwd()), not relative to the module/package file path.

    If you want the path to be relative to the moduel/packages, use __file__:

    def __init__(self, filename="./dic/english_quadgrams.txt"):
        self.filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
        ....