22

来自 R,setwd用于更改目录对可重复性是一个很大的禁忌,因为其他人的目录结构与我的不同。因此,建议使用脚本位置的相对路径。

IDE 稍微复杂化了这一点,因为它们设置了自己的工作目录。在 Rstudio 中,我可以通过 Rstudio 的项目轻松解决这个问题,将项目的目录设置为我的脚本文件夹。

使用 Python 和 Spyder,似乎没有任何解决方案。Spyder 没有像 Rstudio 的项目那样的功能。在进行交互式分析时,将目录设置为脚本的位置不起作用(因为__file__不可用)。

怎么做才能使 Python / Spyder 中的工作目录可重现?

4

6 回答 6

14

要自动执行此操作,请将其放在脚本的开头:

from os import chdir, getcwd
wd=getcwd()
chdir(wd)
于 2017-07-18T20:00:04.167 回答
7

在此期间,您可以使用 os.chdir

import os
os.chdir('C:\Users\me\Documents')
于 2017-01-05T08:25:40.547 回答
4

看来他们确实认为这是基于此 GitHub 票证的 Spyder 中的一项功能,但截至 5 月中旬,它仍在等待实施:

我们可以在“运行”对话框中添加一个选项,以自动将工作目录设置为您的脚本正在运行的目录。

但是,其他人将不得不实施它。我们现在正忙于其他事情,抱歉。

https://github.com/spyder-ide/spyder/issues/3154

@ccordoba12 ccordoba12 于 5 月 14 日将此添加到愿望清单里程碑

于 2016-07-15T12:04:03.470 回答
2

正如我在这里所写,Mark8888指出要运行整个脚本(运行文件 (F5)),而不仅仅是脚本的一部分

这种方式应该可以使用多种方法来获取脚本文件位置并更改当前工作目录

import os
# directory of script file
print(os.path.abspath(os.path.dirname(__file__)))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(__file__)))
# current working directory
print(os.getcwd())

import os
import sys
# directory of script file
print(os.path.abspath(os.path.dirname(sys.argv[0])))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))
# current working directory
print(os.getcwd())
于 2021-04-17T15:15:44.310 回答
1

我试过这个并且它有效。

import os
abspath = os.path.abspath('') ## String which contains absolute path to the script file
os.chdir(abspath) ## Setting up working directory
于 2019-01-21T04:32:17.223 回答
1

嗯,有很多东西可以尝试!1. 将目录更改为工具栏中的当前目录。2. 将 Global 目录更改为 Preferences>Global Working Directory 中的当前目录。单击“当前文件目录”单选按钮。

希望能帮助到你!

于 2017-08-29T16:42:13.160 回答