Prometheus
Prometheus

Reputation: 33605

How to move down to a parent directory in Python?

The following code in Python gives me the current path.

import os
DIR = os.path.dirname(os.path.dirname(__file__))

How can I now use the variable DIR to go down one more directory? I don't want to change the value of DIR as it is used elsewhere.

I have tried this:

DIR + "../path/"

But it does not seems to work.

Upvotes: 0

Views: 3398

Answers (3)

sharpshadow
sharpshadow

Reputation: 1296

When you join a path via '+' you have to add a 'r':

path = r'C:/home/' + r'user/dekstop'

or write double backslashes:

path = 'C://home//' + 'user//dekstop'

Anyway you should never use that!

That's the best way:

import os
path = os.path.join('C:/home/', 'user/dekstop')

Upvotes: 1

Glyn Jackson
Glyn Jackson

Reputation: 8354

Try:

import os.path
print(os.path.abspath(os.path.join(DIR, os.pardir)))

Upvotes: 2

falsetru
falsetru

Reputation: 368944

Call one more dirname:

os.path.join(os.path.dirname(DIR), 'path')

Upvotes: 2

Related Questions