如何使用python 3获取当前的工作目录? [英] How to get the current working directory using python 3?

查看:456
本文介绍了如何使用python 3获取当前的工作目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在IDLE中运行以下脚本时

When I run the following script in IDLE

import os
print(os.getcwd())

我得到的输出为

D:\testtool

但是当我从cmd提示符运行时,我得到了

but when I run from cmd prompt, I get

c:\Python33>python D:\testtool\current_dir.py
c:\Python33

如何获得与使用IDLE相同的结果?

How do I get same result which I got using IDLE ?

推荐答案

IDLE似乎将其当前工作目录更改为执行脚本的位置,而在使用cmd运行脚本时却没有这样做,并且它留下了保持CWD不变.

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())

仅当您从文件执行脚本时,__file__变量才可用,并且该变量包含文件的路径.此处的更多信息: Python __file__属性是绝对还是相对?

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 3获取当前的工作目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆