如何在不知道完整路径的情况下使用 python 访问姐妹目录中的文件

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

我在 folder_a 中有一个文件,我想在 folder_b 中执行一个 bat/bash 文件。这将与朋友共享,所以我不知道他会从哪里 运行 文件。这就是为什么我不知道确切的路径。

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

这是我的代码。 运行没有错误,但没有显示任何内容。

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()

我想尝试只使用内置 Python 库。

简短版本:我认为您的主要问题是每个 cd 之前的 (。但是,还有其他一些东西也可以清理您的代码。

如果您只需要 运行 正确的 batch/bash 文件,您可能不必实际更改当前工作目录。

Python 的内置 pathlib module can be really convenient 用于操作文件路径。

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)

但是,如果批处理文件希望它来自它自己的目录 运行,您可以这样更改它:

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)