S Andrew
S Andrew

Reputation: 7198

How to split out the path received from os.path.dirname()

Lets say I have a python file saved inside the directory

E:\Data\App

So when I did print os.path.dirname(str(sys.argv[0])), it showed me the above path. Now lets say I want to create a new file inside E:\Data\Conf\, so how to cut out App and use Conf and save the file inside E:\Data\Conf

I cannot directly use the complete path because E:\Data\ will not be common and will vary.

Thanks.

Upvotes: 1

Views: 255

Answers (2)

dheiberg
dheiberg

Reputation: 1914

You could do this:

path = 'E:\Data\conf' # Or however you will assign this
dir_path = '\\'.join(path.split('\\')[:-1]) + '\\' # 'E:\Data\'

This basically splits the string of the path by \, then rebuilds the string with all but the last path in the tree.

Upvotes: 1

tzaman
tzaman

Reputation: 47770

from os.path import dirname, join

file_dir = dirname(the_file)
parent_dir = dirname(file_dir)
conf_dir = join(parent_dir, 'Conf')

dirname always gets the directory containing whatever path you pass it, so calling it on your file will get you the app directory; calling it again on the app directory will get you the parent of that. You can then use os.path.join to attach "Conf" or whatever other directory you want.

Another way is using os.path.abspath along with os.pardir to go up any number of levels:

import os
from os.path import abspath, dirname, join

conf_dir = abspath(join(dirname(the_file), os.pardir, "Conf"))
                                         # ^ You can add more of these to go up the heirarchy

The inner join call with os.pardir will construct a path like "E:\Data\App\..\Conf", and abspath will resolve it into "E:\Data\Conf".

Upvotes: 0

Related Questions