wangya87

python中获取文件路径的几种方式

# 如果执行文件为E:\aa\bb\aa.py

1.获取当前路径

current_path11 = os.path.abspath(__file__)      

current_path12 = os.path.realpath(__file__)

# 说明:以上2种方式返回结果一样,均为E:\aa\bb\aa.py

2.获取父路径

pra_path11 = os.path.abspath(os.curdir)

pra_path12 = os.path.dirname(os.path.abspath(__file__))

说明:1.返回结果为E:\aa\bb

   2.区别:pra_path11返回的是执行文件所在文件夹,如果其他文件调用aa.py,则返回其他文件的父路径。

            例如文件E:\aa\cc.py调用aa.py,则返回E:\aa

       pra_path12返回的是aa.py文件所在文件夹,不管谁调用返回均为E:\aa\bb

3.获取父路径的父路径

pra_path2 = os.path.dirname(pra_path12)

返回结果为E:\aa

4.路径连接

方式一,直接用“+”:new_path = pra_path2 + "\\report\\" + "config.ini"

方式二,用join:         new_path = os.path.join(pra_path2,‘report’,\'config.ini\')

#新路径E:\aa\report\config.ini

5.创建路径

 if not os.path.exists(new_path):

  os.makedirs(new_path)

 

发表于 2020-07-08 09:19  inoey  阅读(4214)  评论(0编辑  收藏  举报
 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-11-29
  • 2022-12-23
  • 2022-12-23
  • 2021-11-18
  • 2021-05-26
猜你喜欢
  • 2022-12-23
  • 2021-12-10
  • 2021-12-25
  • 2022-12-23
  • 2021-07-03
  • 2022-02-07
  • 2022-12-23
相关资源
相似解决方案