Python os.path.join getting to upper directory

Started by
2 comments, last by Black Knight 13 years, 8 months ago
Hi guys, I am trying to get to a upper directory and then to subfolders of that with os.path.join.

Seems to work on windows but I am wonder if it works on Unix too.

So imagine there are 2 folders in the same folder called foo and bar and there is a script is run in foo folder.So the current working directory is foo. Now I want to change the current working folder to bar and later to its sub folders.

newPath = os.path.join('..','bar')
newPath = os.path.join(newPath,'someSubFolderofBar')
newPath = os.path.join(newPath,'anotherSubfolderofBar')
os.chdir(newPath)

Is this the correct way?
Advertisement
Quote:Original post by Black Knight
Hi guys, I am trying to get to a upper directory and then to subfolders of that with os.path.join.

Seems to work on windows but I am wonder if it works on Unix too.

So imagine there are 2 folders in the same folder called foo and bar and there is a script is run in foo folder.So the current working directory is foo. Now I want to change the current working folder to bar and later to its sub folders.

newPath = os.path.join('..','bar')
newPath = os.path.join(newPath,'someSubFolderofBar')
newPath = os.path.join(newPath,'anotherSubfolderofBar')
os.chdir(newPath)

Is this the correct way?


Should be fine. But did you know os.path.join can take more that two arguments?

newPath = os.path.join('..','bar','someSubFolderofBar','anotherSubfolderofBar')


If you wanted to be super-portable, you should use os.path.pardir instead of '..'. But if you're only targeting POSIX systems and Windows, '..' is fine.

EDIT: actually, I'm not 100% sure if you mean that the script you're running is in foo/ or if the current working directory is foo/.

To get the location of the current python file, you can do:

scriptdir = os.path.dirname(__file__)


Here is the real deal :)

There is an application inside the foo folder and it is run from somewhere,this application is not a python script but the current working folder is foo. This application then runs a python script inside bar/folder1/folder2.

The script needs to change the current folder to bar/folder1/folder2 so it can find data files in the same folder as it is.

Thanks for the info ill combine them to one line.

How do you use os.path.pardir? I can't seem to find an example.

Nevermind I got it:

newPath = os.path.join(os.pardir,'bar','someSubFolderofBar','anotherSubfolderofBar')

This topic is closed to new replies.

Advertisement