os.path.split()、os.path.realpath()和os.path.join()

1. 前提

有一个文件ReadConfigIni.py,这个文件的路径是 D:\SoftWare\autoTest\AutoRunTest\Public\Common\ReadConfigIni.py

2. os.path.realpath(__file__)

os.path.realpath(__file__)获取当前文件的绝对路径__file__指当前文件,在ReadConfigIni.py文件中运行以下代码

# 当前文件路径
fp = os.path.realpath(__file__)
print (fp)
#输出结果
D:\SoftWare\autoTest\AutoRunTest\Public\Common\ReadConfigIni.py

3. os.path.split()

os.path.split("PATH") 参数说明:

(1)PATH指一个文件的全路径(绝对路径)作为参数

(2) 如果给出的是一个目录和文件名,则输出路径和文件名,输出为tuple

(3)如果给出的是一个目录名,则输出路径和空文件名,输出为tuple

实际上,该函数的分割并不智能,它仅仅是以"PATH"中的最后一个"/"作为分隔符,分隔后,将索引为0的视为目录(路径),将索引为1的视为文件名。

file_path = os.path.split("D:/SoftWare/autoTest/AutoRunTest/Public/Common/ReadConfigIni.py")
print (file_path)
# 输出结果
# ('D:/SoftWare/autoTest/AutoRunTest/Public/Common/', 'ReadConfigIni.py')

file_path = os.path.split("D:/SoftWare/autoTest/AutoRunTest/Public/Common/")
print (file_path)
# 输出结果
# ('D:/SoftWare/autoTest/AutoRunTest/Public/Common/', '')
file_path = os.path.split("D:/SoftWare/autoTest/AutoRunTest/Public/Common/ReadConfigIni.py")[0]
print (file_path)
# 输出结果
# D:/SoftWare/autoTest/AutoRunTest/Public/Common/

file_path = os.path.split("D:/SoftWare/autoTest/AutoRunTest/Public/Common/ReadConfigIni.py")[1]
print (file_path)
# 输出结果
# ReadConfigIni.py

split()函数

如何解决分割不智能的这个弊端呢?可以直接使用对字符串进行操作的split()函数 。在命令行中演示一下。

4.os.path.join()

os.path.join()在路径后追加
os.path.join(file_path,"config.ini")
即:D:\SoftWare\autoTest\AutoRunTest\Public\Common\config.ini
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值