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

Time:10-15

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?

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.

CodePudding user response:

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

  • Related