简体   繁体   English

Spyder/Python - 自动将工作目录设置为当前脚本的

[英]Spyder/Python - Automatically set working directory to current script's

I know that the directory can be automatically changed to that of the current script if we press F5.我知道如果我们按 F5,目录可以自动更改为当前脚本的目录。

But is there a way to automatically do so when I run the codes in interactive mode, or when I open a script?但是,当我以交互模式运行代码或打开脚本时,有没有办法自动执行此操作? Currently I need to os.chdir() to the current working directory.目前我需要 os.chdir() 到当前工作目录。

Thanks.谢谢。

You can add the following lines to your script:您可以将以下行添加到您的脚本中:

import os
os.chdir(os.path.dirname(__file__))

__file__ will return the path of the script, and we can use os.path.dirname to find which directory it is located in. Then just use os.chdir to change to that directory. __file__将返回脚本的路径,我们可以使用os.path.dirname找到它所在的目录。然后只需使用os.chdir切换到该目录。

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

相关问题 在 Python / Spyder 中设置工作目录,使其可重现 - Set working directory in Python / Spyder so that it's reproducible Spyder 3“设置控制台工作目录”无法正常工作 - Spyder 3 “Set Console Working Directory” not working 在 Python 中更改调用者的当前工作目录 - Change caller's current working directory in Python Spyder - 如何在当前控制台中执行 python 脚本? - Spyder - how to execute python script in the current console? 您如何在python中收获当前用户和脚本的工作目录? - How can you harvest the current user and script's working directory in python? 如何在 Spyder 上获取当前脚本的目录(不使用“__file__”)? - How to get the directory of a current script on Spyder (without using '__file__')? Hive在Python脚本中调用时尝试读取当前工作目录 - Hive trying to read current working directory when called in Python script 如何获取 Atom 的脚本 package 以从脚本的当前工作目录运行脚本? - How can I get Atom's script package to run a script from the script's current working directory? python:将脚本工作目录更改为脚本自己的目录 - python: Change the scripts working directory to the script's own directory Python:将脚本的工作目录更改为其他目录以读取常量 - Python: Change the script's working directory to a different directory to read constants
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM