Python: os.getcwd() 重构后文件位置不变

Python: os.getcwd() unchanged after refactor file location

说我在 path/to/somewhere/ 下创建 a.py。后来在 IDE(pycharm) 中,我将其重构为 path/to/another_place/.

但是当我运行a.py之后,os.getcwd()显示它的工作目录还在path/to/somewhere。 (os.listdir('.') 也显示它在原来的地方。)

下图是我遇到的makeimg.py原来是在learn_function

我是 python 的新手,我不明白 file/modoule 是如何定位自己的。

我是不是做错了什么?还是错误?

os.getcwd() returns c当前w工作d目录,它 may/may 不是您的脚本所在的目录,它是脚本所在的目录 运行。很可能在您的 PyCharm Run/Debug 配置中,您已将工作目录设置为 path/to/somewhere .

run/debug configuration doc page 到 pycharm -

Working directory - Specify a directory to be used by the running task.

When a default run/debug configuration is created by the keyboard shortcut Ctrl+Shift+F10 , or by choosing Run on the context menu of a script, the working directory is the one that contains the executable script. This directory may differ from the project directory.

理想情况下,您的代码不应依赖于当前工作目录,因为您可以使用 python 文件的绝对路径从任何地方 运行 一个 python 文件。

相反,如果您想要脚本所在的路径,请使用 __file__ 在脚本中获取该路径。

例子-

print(__file__)

这应该打印脚本的路径(如 sys.argv[0] 中给出的)。