python工作目录_如何使用python 3获取当前工作目录?
When I run the following script in IDLE
import os
print(os.getcwd())
I get output as
D:\testtool
but when I run from cmd prompt, I get
c:\Python33>python D:\testtool\current_dir.py
c:\Python33
How do I get same result which I got using IDLE ?
解決方案
It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.
To change current working dir to the one containing your script you can use:
import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())
The __file__ variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?
總結
以上是生活随笔為你收集整理的python工作目录_如何使用python 3获取当前工作目录?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue slot scope使用_20、
- 下一篇: python调用报表制作工具_使用Pyt