简体   繁体   中英

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 idk 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

heres 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

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

Python's built-in pathlib module can bereally 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.
files_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(files_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

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

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

os.chdir(files_dir / 'modules')
os.system(file_name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM