gpt4 book ai didi

python - 删除字符串中的最后一个路径组件

转载 作者:IT老高 更新时间:2023-10-28 21:41:22 26 4
gpt4 key购买 nike

我有一条路:

myPath = "C:\Users\myFile.txt"

我想删除结束路径,以便字符串只包含:

"C:\Users"

到目前为止,我正在使用拆分,但它只是给了我一个列表,我卡在这一点上。

myPath = myPath.split(os.sep)

最佳答案

你不应该直接操作路径,有 os.path 模块。

>>> import os.path
>>> print os.path.dirname("C:\Users\myFile.txt")
C:\Users
>>> print os.path.dirname(os.path.dirname("C:\Users\myFile.txt"))
C:\

像这样。

关于python - 删除字符串中的最后一个路径组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3315045/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com