简体   繁体   English

如何从文件路径中删除子目录名称

[英]How to remove sub-directory name from filepath

dirpath variable points to a directory with two sub-folders both named 'Temp': dirpath变量指向一个目录,该目录包含两个都名为“ Temp”的子文件夹:

dirpath='C:/Users/Temp/AppData/Local/Temp'

Another variable word stores the name of directory that needs to removed from dirpath but only if it is a last sub-folder: 另一个变量word存储需要从目录dirpath删除的目录名称,但dirpath是它是最后一个子文件夹:

word='temp'

So the final result should be: 因此,最终结果应为:

result='C:/Users/Temp/AppData/Local'

Please note the "Temp" in dirpath starts with uppercase. 请注意, dirpath的“ Temp”以大写字母开头。 While the word variable defines 'temp' in lower case. word变量定义小写的“ temp”。 The final result should preserve original upper case characters used in dirpath variable . 最终结果应保留dirpath变量中使用的原始大写字符。

How to achieve this with a minimum code? 如何用最少的代码实现这一目标?

You should try to work with the "os" module . 您应该尝试使用“ os”模块

In particular to the following two functions: 特别要实现以下两个功能:

os.path.join() and os.path.split() os.path.join()和os.path.split()

If you use os.path.split() then you can use os.path join to get the final path when you remove the last component of the list. 如果使用os.path.split(),则在删除列表的最后一个组件时可以使用os.path join获取最终路径。 In your case the first split would give you what you want. 在您的情况下,第一次拆分将满足您的需求。

>>> import os
>>> dirpath='C:/Users/Temp/AppData/Local/Temp'
>>> dirpath
'C:/Users/Temp/AppData/Local/Temp'
>>> os.path.split(dirpath)
('C:/Users/Temp/AppData/Local', 'Temp')
>>> result = os.path.split(dirpath)
>>> result[0]
'C:/Users/Temp/AppData/Local'
>>> 

Use the regular expression module re 使用正则表达式模块re

import re
dirpath = 'C:/Users/Temp/AppData/Local/Temp'
word = 'temp'

if re.search("/%s$"%word, dirpath.lower()):
    dirpath = dirpath[:-len(word)] 

print dirpath

Maybe you combine this with the first answer, I'm not that good with the os -module 也许您将其与第一个答案结合起来,但我对os -module的评价不高

dirpath='C:/Users/Temp/AppData/Local/Temp'
word='temp'

if dirpath.lower().endswith(word.lower()):
    dirpath=dirpath[:-(len(word)+1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM