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

How to get to a file in sister directory with python without knowing the full path

I have a file in folder_a and I want to execute a bat/bash file in folder_b. This will be shared with a friend, so I don’t know where he’ll run the file from. That’s why I don’t know the exact path.

folder_a
  ___
 |   |
 |   python.py
 |folder_b
 |___
 |   |
 |   bat/bash file

Here’s my code. It runs without errors, but it doesn’t display anything.

import os, sys
def change_folder():
        current_dir = os.path.dirname(sys.argv[0])
        filesnt = "(cd "+current_dir+" && cd .. && cd modules && bat.bat"
        filesunix = "(cd "+current_dir+" && cd .. && cd modules && bash.sh"
        if os.name == "nt":
            os.system(filesnt)
        else:
            os.system(filesunix)
inputtxt = input()
if inputtxt == "cmd file":
        change_folder()

I would like to try to use only builtin Python libraries.

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

>Solution :

The short version: I believe your main problem is with the ( before each cd. However, there are other things that could clean up your code as well.

If you only need to run the correct batch/bash file, you might not have to actually change the current working directory.

Python’s built-in pathlib module can be really convenient for manipulating file paths.

import os
from pathlib import Path

# Get the directory that contains this file's directory and the modules
# directory. Most of the time __file__ will be an absolute (rather than
# relative) path, but .resolve() insures this.
top_dir = Path(__file__).resolve().parent.parent

# Select the file name based on OS.
file_name = 'bat.bat' if os.name == 'nt' else 'bash.sh'

# Path objects use the / operator to join path elements. It will use the
# correct separator regardless of platform.
os.system(top_dir / 'modules' / file_name)

However, if the batch file expects it to be run from its own directory, you could change to it like this:

import os
from pathlib import Path

top_dir = Path(__file__).resolve().parent.parent

file_name = 'bat.bat' if os.name == 'nt' else 'bash.sh'

os.chdir(top_dir / 'modules')
os.system(file_name)
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