Python:操作系统getcwd()重构文件位置后保持不变

2024-04-25 00:45:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但是当我以后运行a.py时,os.getcwd()显示它的工作目录仍然在path/to/somewhere中。(os.listdir('.')还显示它在原始位置。)

下面的图片是我遇到的picturemakeimg.py最初在learn_function

我是python新手,不知道文件/模块如何定位自己。在

我做错什么了吗?或者是虫子?在


Tags: topathpy目录osanother图片place
1条回答
网友
1楼 · 发布于 2024-04-25 00:45:11

os.getcwd()返回ccurrentwworkingd目录,它可能/可能不是脚本所在的目录,而是运行脚本的目录。很可能在PyCharm Run/Debug配置中,您已经将工作目录设置为path/to/somewhere。在

来自^{} 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]中所示)。在

相关问题 更多 >