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

Time:01-03

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.

CodePudding user response:

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)
  • Related