查找当前目录和文件所在目录 [英] Find the current directory and file's directory
本文介绍了查找当前目录和文件所在目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Python 中,我可以使用哪些命令来查找:
In Python, what commands can I use to find:
- 当前目录(运行 Python 脚本时我在终端中的位置),以及
- 我正在执行的文件在哪里?
推荐答案
要获取包含 Python 文件的目录的完整路径,请在该文件中写入:
To get the full path to the directory a Python file is contained in, write this in that file:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
(请注意,如果您已经使用 os.chdir()
更改当前工作目录,则上面的咒语将不起作用,因为 __file__
的值> 常量相对于当前工作目录,不会被 os.chdir()
调用更改.)
(Note that the incantation above won't work if you've already used os.chdir()
to change your current working directory, since the value of the __file__
constant is relative to the current working directory and is not changed by an os.chdir()
call.)
获取当前工作目录使用
import os
cwd = os.getcwd()
<小时>
上面使用的模块、常量和函数的文档参考:
Documentation references for the modules, constants and functions used above:
os
和os.path
模块.__file__
常量os.path.realpath(path)
(返回指定文件名的规范路径,消除路径中遇到的任何符号链接")os.path.dirname(path)
(返回路径名path
"的目录名)os.getcwd()
(返回"表示当前工作目录的字符串")os.chdir(path)
("将当前工作目录更改为path
")
这篇关于查找当前目录和文件所在目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文