I am writing a python script 2.5 in Windows whose CurrentDir = C:\users\spring\projects\sw\demo753円\ver1.1011円\rev120\source my file is test.py. From this path I would like to access files in this path: C:\users\spring\projects\sw\demo753円\ver1.1011円\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")
-
Post some code. What's not working?Adam Rosenfield– Adam Rosenfield2011年07月12日 06:05:51 +00:00Commented Jul 12, 2011 at 6:05
-
Code snippet would be helpful in tracking down the problem.Sanjay– Sanjay2011年07月12日 06:06:13 +00:00Commented Jul 12, 2011 at 6:06
-
Why are you using an ancient python version?ThiefMaster– ThiefMaster2011年07月12日 06:14:22 +00:00Commented Jul 12, 2011 at 6:14
-
@ThiefMaster My environment has a number of internal tools all based on python 2.5 so can't break itspring– spring2011年07月12日 06:29:27 +00:00Commented Jul 12, 2011 at 6:29
-
Sounds like those tools should be tested with 2.6/2.7 (which should be easy since those versions do not introduce many changes which might break things) instead of keeping such an old version.ThiefMaster– ThiefMaster2011年07月12日 06:30:52 +00:00Commented Jul 12, 2011 at 6:30
3 Answers 3
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")
Comments
from os.path import dirname, join
join(dirname(dirname(__file__)), 'Common')
should work.
4 Comments
os.path.join(os.path.dirname(os.path.dirname(__file__)), 'Common')join to be from os.path but rather something more generic...Try this:
joined = os.path.join('C:\\users\\spring\\projects\\sw\\demo\753円\\ver1.1\011円\\rev120\\source', '..\\Common\\')
# 'C:\\users\\spring\\projects\\sw\\demo\753円\\ver1.1\011円\\rev120\\source\\..\\Common\\'
canonical = os.path.realpath(joined)
# 'C:\\users\\spring\\projects\\sw\\demo\753円\\ver1.1\011円\\rev120\\Common'
4 Comments
join() did not remove the ... I agree though that the path is usable as it is and the call to realpath() is completely unnecessary.os.path.join(os.getcwd(), '..\\Common')?