Python中的__file__变量
python中的__file__变量给出了.py文件的位置,例如在test.py中
print(__file__)
打印之后,即可得到test.py的位置/home/user/test.py
常用的方法是结合os.path.abspath(os.path.dirname(__file__)),得到.py文件的所在目录的绝对路径,从而构造出同目录下另一文件的绝对路径
import os
basedir = os.path.abspath(os.path.dirname(__file__))
abs_path_to_another = (os.path.join(basedir,'another'))
本文详细介绍了Python中__file__变量的作用和使用方法,解释了如何利用它获取.py文件的位置及所在目录的绝对路径,进而构造同目录下其他文件的绝对路径。
384

被折叠的 条评论
为什么被折叠?



