1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python分隔符的使用 在python中使用分隔符“\”拆分字符串

python分隔符的使用 在python中使用分隔符“\”拆分字符串

时间:2022-05-30 03:57:28

相关推荐

python分隔符的使用 在python中使用分隔符“\”拆分字符串

这里有两个问题。在

路径分割

通常使用os.path.split来处理路径:>>> import os.path

>>> p=r'C:\Users\xyz\filename.txt'

>>> head, tail = os.path.split(p)

>>> head

'C:\\Users\\xyz'

>>> tail

'filename.txt'

注意:os.path使用它所使用的操作系统的路径格式。如果您知道您特别想使用Windows路径(即使您的程序是在Linux或OSX上运行的),那么您应该使用os.path模块而不是ntpath模块。See the note:Note Since different operating systems have different path name conventions, there are several versions of this module in the standard library. The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats. They all have the same interface:posixpath for UNIX-style paths

ntpath for Windows paths

macpath for old-style MacOS paths

os2emxpath for OS/2 EMX paths

格式支持

有两种格式可支持:在文件://C:\Users\xyz\文件名.txt在

C: \用户\xyz\文件名.txt在

2是正常的Windows路径,1是。。。坦白说,我不知道那是什么。它看起来有点像file URI,但使用了Windows样式的分隔符(反斜杠)。这很奇怪。当我在Windows上用Chrome打开PDF时,URI看起来不一样:

^{pr2}$

我假设这就是你感兴趣的格式。如果没有,那么我不能保证你在处理什么,你可以对如何解释它做一些有根据的猜测(去掉file://前缀,将其视为Windows路径?)。在

可以使用the ^{} module将一个URI拆分成有意义的部分(参见python3的urllib.parse),一旦提取了URI的路径部分,就可以.split('/')它(URI语法非常简单,可以实现这一点)。如果在file://URI上使用此模块,会发生以下情况:>>> r = urlparse.urlparse(r'file:///C:/Users/xyz/filename.txt')

>>> r

ParseResult(scheme='file', netloc='', path='/C:/Users/xyz/filename.txt', params='', query='', fragment='')

>>> r.path

'/C:/Users/xyz/filename.txt'

>>> r.path.lstrip('/').split('/')

['C:', 'Users', 'xyz', 'filename.txt']

请阅读this URI scheme description以更好地了解此格式的外观,以及为什么file:后面有三个斜杠。在

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。