【问题标题】:How to get to a file in sister directory with python without knowing the full path如何在不知道完整路径的情况下使用 python 访问姊妹目录中的文件
【发布时间】:2022-01-03 02:05:41
【问题描述】:

我在 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 库。

【问题讨论】:

  • pushd ../modules?
  • 是的,我现在把它修好了'
  • 什么是cmodulesnt/modulesunix 应该是filesnt/filesunix 吗?
  • @chepner 我有一个 os.system 作为 c 的快捷方式,是的,它是 filent 和 filesunix 我现在修复了它
  • change_folder() 之后的最终: 实际上在您的代码中吗?它应该抛出一个语法错误。

标签: python bash directory


【解决方案1】:

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

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

Python 内置的pathlib 模块可以是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)

【讨论】:

    最近更新 更多