繁体   English   中英

如何在不知道完整路径的情况下使用 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 库

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

Python 内置的pathlib模块可以非常方便地操作文件路径。

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)

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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