python os path_Python os.path.commonpath()用法及代码示例

Python中的OS模块提供了与操作系统进行交互的功能。操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的功能的便携式方法。 os.path模块是Python中OS模块的子模块,用于通用路径名操作。

os.path.commonpath()Python中的方法用于获取路径列表中最长的通用sub-path。如果指定的路径列表包含绝对路径和相对路径,或者为空,则此方法引发ValueError。不像os.path.commonpath()方法,返回的值是有效路径。

例如,考虑以下路径列表:

list of paths Longest common sub-path

['/home/User/Photos', /home/User/Videos'] /home/User

['/usr/local/bin', '/usr/lib'] /usr

用法: os.path.commonpath(list)

参数:

path:path-like对象的列表。 path-like对象是表示路径的字符串或字节对象。

返回类型:此方法返回一个字符串值,该字符串值表示指定列表中最长的公用sub-path。

代码1:使用os.path.commonpath()方法

# Python program to explain os.path.commonpath() method

# importing os module

import os

# List of Paths

paths = ['/home/User/Desktop', '/home/User/Documents',

'/home/User/Downloads']

# Get the

# longest common sub-path

# in the specified list

prefix = os.path.commonpath(paths)

# Print the

# longest common sub-path

# in the specified list

print("Longest common sub-path:", prefix)

# List of Paths

paths = ['/usr/local/bin', '/usr/bin']

# Get the

# longest common sub-path

# in the specified list

prefix = os.path.commonpath(paths)

# Print the

# longest common sub-path

# in the specified list

print("Longest common sub-path:", prefix)

输出:

Longest common sub-path: /home/User

Longest common sub-path: /usr

代码2:使用os.path.commonpath()方法

# Python program to explain os.path.commonpath() method

# importing os module

import os

# List of Paths

paths = ['/usr/local/bin', 'usr/bin']

# Get the

# longest common sub-path

# in the specified list

prefix = os.path.commonpath(paths)

# Print the

# longest common sub-path

# in the specified list

print("Longest common sub-path:", prefix)

# The above code will raise

# ValueError as list of paths

# contains both absolute and

# relative path

输出:

Traceback (most recent call last):

File "oscommonpath.py", line 12, in

prefix = os.path.commonpath(paths)

File "/usr/lib/python3.6/posixpath.py", line 505, in commonpath

raise ValueError("Can't mix absolute and relative paths") from None

ValueError: Can't mix absolute and relative paths

注意:如果指定的列表为空,os.path.commonpath()方法也会引发ValueError。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值