如何确定:
网友回答:
当前工作目录:os.getcwd()
该属性可以帮助您找出正在执行的文件所在的位置。这篇堆栈溢出帖子解释了一切:如何在 Python 中获取当前执行文件的路径?__file__
网友回答:
您可能会发现这作为参考很有用:
import os
print("Path at terminal when executing this file")
print(os.getcwd() + "n")
print("This file path, relative to os.getcwd()")
print(__file__ + "n")
print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "n")
print("This file directory and name")
path, filename = os.path.split(full_path)
print(path + ' --> ' + filename + "n")
print("This file directory only")
print(os.path.dirname(full_path))
网友回答:
要获取包含 Python 文件的目录的完整路径,请将以下内容写入该文件:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
(请注意,如果您已经习惯了更改当前工作目录,则上面的咒语将不起作用,因为常量的值是相对于当前工作目录的,并且不会通过调用更改。os.chdir()
__file__
os.chdir()
获取当前工作目录使用
import os
cwd = os.getcwd()
上面使用的模块、常量和函数的文档参考:
os
os.path
__file__
os.path.realpath(path)
(返回“指定文件名的规范路径,消除路径中遇到的任何符号链接”)os.path.dirname(path)
(返回“路径名路径
的目录名”)os.getcwd()
(返回“表示当前工作目录的字符串”)os.chdir(path)
(“将当前工作目录更改为路径
”)模板简介:该模板名称为【如何正确确定当前脚本目录?查找当前目录和文件的目录】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。