分割并重新加入路径而不会在后面加上反斜杠 [英] Split and rejoin path without trailing backslash

查看:64
本文介绍了分割并重新加入路径而不会在后面加上反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的新手,当我执行Frankensplice *路径时,我会得到一个额外的反斜杠.不知道为什么.我知道它在原始状态下打印为"\".这是在Windows计算机上发生的.

New to Python, when I Frankensplice* a path, I'm pick up an extra backslash. Not sure why. I'm aware that it prints out as '\' in the raw state. This is happening on a Windows machine.

*(将其拆分,然后再次放回原处)

*(split it and then put it back together again)

这就是我所拥有的

import os

f = "C:\\Gwen\\Stefani\\This is bananas.txt"

fname, ext = os.path.splitext(f)
head, tail = os.path.split(fname)

# strip last slash
tail = tail.rstrip("\\")

print ("%r" % (f))    # 'C:\\Gwen\\Stefani\\This is bananas.txt'
print ("%r" % (head)) # 'C:\\Gwen\\Stefani'
print ("%r" % (tail)) # 'This is bananas'
print ("%r" % (ext))  # '.txt'

# join them again
r = os.path.join(head, tail, ext)
print ("%r" % (r)) # 'C:\\Gwen\\Stefani\\This is bananas\\.txt'

推荐答案

os.path.split拆分路径\文件"时,所有反斜杠都将被删除,因此无需执行tail.rstrip("\\").

When os.path.split splits the "path\file", all the backslashes are removed, so there is no need to do the tail.rstrip("\\").

此外,当将它们重新添加以获取相同的文本时,您需要执行以下操作:

Further, when adding them back to get the identical text you need to do the following:

r = os.path.join(head, tail, fname + ext)

这是因为os.path.join连接路径元素,并且可能无法知道您突然只引入了文件名的一部分(.ext).换句话说,您需要先连接文件名,然后再加入完整的文件路径. (这与您使用splitext拆分文件名...相反)

This is because os.path.join joins path elements, and can't possibly know that you are suddenly introducing only part of a filename (the .ext). In other words, you need to concatenate the filename before joining to the complete filepath. (This is the reverse of your need to use splitext to split the filename... )

这篇关于分割并重新加入路径而不会在后面加上反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆