Python——获取当前路径

Python——获取当前路径,第1张

1. 获得该文件的绝对路径
os.path.abspath(__file__)
2. 获得该文件所在的真实全部路径
os.path.realpath(__file__)
3. 获得该文件所在的文件夹路径
os.path.split(os.path.realpath(__file__))[0]
示例
import os
import sys

print("sys.path[0] = ", sys.path[0])
print("sys.argv[0] = ", sys.argv[0])
print("__file__ = ", __file__)
print("os.path.abspath(__file__) = ", os.path.abspath(__file__))
print("os.path.realpath(__file__) = ", os.path.realpath(__file__))
print("os.path.dirname(os.path.realpath(__file__)) = ", 
       os.path.dirname(os.path.realpath(__file__)))
print("os.path.split(os.path.realpath(__file__)) = ", 
       os.path.split(os.path.realpath(__file__)))
print("os.path.split(os.path.realpath(__file__))[0] = ", 
       os.path.split(os.path.realpath(__file__))[0])
print("os.getcwd() = ", os.getcwd())
C:\PyCharm\PycharmProject\get_path>python path_demo.py
('sys.path[0] = ', 'C:\PyCharm\PycharmProject\get_path')
('sys.argv[0] = ', 'path_demo.py')
('__file__ = ', 'path_demo.py')
('os.path.abspath(__file__) = ', 'C:\PyCharm\PycharmProject\get_path\path_demo.py')
('os.path.realpath(__file__) = ', 'C:\PyCharm\PycharmProject\get_path\path_demo.py')
('os.path.dirname(os.path.realpath(__file__)) = ', 'C:\PyCharm\PycharmProject\get_path')
('os.path.split(os.path.realpath(__file__)) = ', ('C:\PyCharm\PycharmProject\get_path', 'path_demo.py'))
('os.path.split(os.path.realpath(__file__))[0] = ', 'C:\PyCharm\PycharmProject\get_path')
('os.getcwd() = ', 'C:\PyCharm\PycharmProject\get_path')

参考文章:

  • Python获取当前文件路径

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/714000.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存