pythonpath-manipulation

Manipulating paths in python


I am writing a python script 2.5 in Windows whose CurrentDir = C:\users\spring\projects\sw\demo\753\ver1.1\011\rev120\source my file is test.py. From this path I would like to access files in this path: C:\users\spring\projects\sw\demo\753\ver1.1\011\rev120\Common\

I tried using os.path.join but it does not work and I from the docs I understand why. So what could be the best pythonic solution for this?

currentdir = os.getcwd()    
config_file_path =  os.path.join(currentdir,"\\..\\Common")

Solution

  • Your problem can be solved by using os.path.join, but you're not using it properly.

    currentdir = os.getcwd()    
    config_file_path =  os.path.join(currentdir,"\\..\\Common")
    

    "\\..\\Common" is not a relative path, as it starts with \.

    You need to join with ..\\Common, which is a relative path.

    Please note that os.path.join is not a simple string concatenation function, you don't need to insert the in-between antislashes.

    So fixed code would be :

    config_file_path =  os.path.join(currentdir,"..\\Common")
    

    or, alternatively :

    config_file_path =  os.path.join(currentdir, "..", "Common")