How to get the current working directory using python 3?

谁说我不能喝 提交于 2019-11-27 13:23:47

问题


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 ?


回答1:


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?




回答2:


Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded. Ref: docs

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

Doc ref: link



来源:https://stackoverflow.com/questions/17359698/how-to-get-the-current-working-directory-using-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!