当我在空闲运行下面的脚本如何使用python 3获取当前工作目录?
import os
print(os.getcwd())
我得到的输出
D:\testtool
,但是当我从命令提示符运行,我得到
c:\Python33>python D:\testtool\current_dir.py
c:\Python33
如何获得相同我使用IDLE的结果?
当我在空闲运行下面的脚本如何使用python 3获取当前工作目录?
import os
print(os.getcwd())
我得到的输出
D:\testtool
,但是当我从命令提示符运行,我得到
c:\Python33>python D:\testtool\current_dir.py
c:\Python33
如何获得相同我使用IDLE的结果?
看来,IDLE将其当前工作目录更改为执行脚本的位置,而使用cmd运行脚本时不会这样做,并且它会使CWD保持原样。
要改变当前的工作目录包含你的脚本,你可以使用一个:只有当您从文件执行脚本
import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())
的__file__
变量可用,它包含文件路径。更多关于它在这里:Python __file__ attribute absolute or relative?
import pathlib
current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)
参考文件:link
给予适当的描述,你的答案 –