Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get path independ from os and create file two defined dirs up?

i try to run a pythonscript (test.py) manually from a folder and it needs to determine the path depending on os and have to create a file two folders up.

Like this:

projectfolder
|-created_file
|
-folder1
 |
 |
 -folder2
  |-test.py

How do i get the path depending on the os? And how do i remove the path parts folder2, folder1 and / or \ (depending on os) to get the root of the project?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This file should be able to run via click. I already tried some solutions without success.

Do you guys have a clue?

Thank you for helping.

>Solution :

import os
open(os.path.join(os.path.dirname(__file__), '..', '..', 'test.txt'), 'w')

The TREE Path

\---projectfolder
|   test.txt
|
\---folder1
    \---folder2
            test.py

Details

You first get the current directory of your script by using

os.path.dirname( __ file __ )

Normally we use ".." to go up one directory

So you join the directory path with 2 folders up using ..

os.path.join()

You can read the full docs here os.path

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading