Skip to main content
 首页 » 编程设计

python之在不同文件夹中执行 .py 文件时是否可以更改工作目录

2025年05月04日13jirigala

例如,这是我的目录树:

+--- test.py 
| 
+--- [subdir] 
      | 
      +--- another.py 

测试.py:

import os 
os.system('python subdir/another.py') 

另一个.py:

import os 
os.mkdir('whatever') 

运行 test.py 后,我希望在 subdir 中有一个文件夹 whatever,但我得到的是:

+--- test.py 
| 
+--- [subdir] 
|     | 
|     +--- another.py 
| 
+--- whatever 

原因很明显:工作目录没有更改为subdir。那么在不同文件夹中执行.py文件时是否可以更改工作目录? 注意:

  1. 允许任何功能,os.system只是一个例子
  2. os.system('cd XXX') 和 os.chdir 不允许

编辑: 最后我决定使用上下文管理器,在
中找到答案 https://stackoverflow.com/posts/17589236/edit

import os 
import subprocess # just to call an arbitrary command e.g. 'ls' 
 
class cd: 
    def __init__(self, newPath): 
        self.newPath = newPath 
 
    def __enter__(self): 
        self.savedPath = os.getcwd() 
        os.chdir(self.newPath) 
 
    def __exit__(self, etype, value, traceback): 
        os.chdir(self.savedPath) 
 
# Now you can enter the directory like this: 
with cd("~/Library"): 
   # we are in ~/Library 
   subprocess.run("ls") 
 
# outside the context manager we are back where we started. 

请您参考如下方法:

你确实可以使用 os.chdir 但依赖于当前工作目录实际是什么的假设是在寻找麻烦,在你的情况下这适用于 os.system 也调用 test.py - 尝试从其他任何地方执行 test.py,您会发现原因。

安全的方法是从 __file__ 属性导出当前模块/脚本的绝对路径,并为 中对 os.system 的调用构建绝对路径test.py 和 another.py

中对 os.mkdir 的调用

要获取当前模块或脚本目录的绝对路径,只需使用:

import os 
ABS_PATH = os.path.dirname(os.path.abspath(__file__))