查找当前目录和文件的目录 [英] Find current directory and file's directory
问题描述
在Python中,可以使用什么命令查找:
- 当前目录Python脚本)和
- 我正在执行的文件是哪里?
要获取包含Python文件的目录的完整路径,请在该文件中写入:
import os
dir_path = os.path.dirname(os.path.realpath(__ file__))
(请注意,如果您已经使用 os.chdir()
来更改您当前的工作目录,则上述咒语将无法正常工作,因为 __ file __
常量是相对于当前工作目录,并且不被 os.chdir()
调用更改。 / p>
要获取当前工作目录使用
import os
cwd = os.getcwd()
文档参考es用于上面使用的模块,常量和函数:
-
os
和os.path
模块。 -
__ file __
常量 -
os.path.realpath(path)
(返回指定文件名的规范路径,消除路径中遇到的任何符号链接) -
os.path.dirname(path)
(返回目录名称路径名路径
) -
os.getcwd()
(返回表示当前工作目录的字符串)< /李>
-
os.chdir(path)
(将当前工作目录更改为路径
)
In Python, what commands can I use to find:
- the current directory (where I was in the terminal when I ran the Python script), and
- where the file I am executing is?
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__))
(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.)
To get the current working directory use
import os
cwd = os.getcwd()
Documentation references for the modules, constants and functions used above:
- The
os
andos.path
modules. - The
__file__
constant os.path.realpath(path)
(returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")os.path.dirname(path)
(returns "the directory name of pathnamepath
")os.getcwd()
(returns "a string representing the current working directory")os.chdir(path)
("change the current working directory topath
")
这篇关于查找当前目录和文件的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!