Reputation: 19349
dirpath
variable points to a directory with two sub-folders both named '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='temp'
So the final result should be:
result='C:/Users/Temp/AppData/Local'
Please note the "Temp" in dirpath
starts with uppercase. While the word
variable defines 'temp' in lower case. The final result should preserve original upper case characters used in dirpath
variable .
How to achieve this with a minimum code?
Upvotes: 0
Views: 117
Reputation: 101
You should try to work with the "os" module.
In particular to the following two functions:
os.path.join() and 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. 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'
>>>
Upvotes: 2
Reputation: 19349
dirpath='C:/Users/Temp/AppData/Local/Temp'
word='temp'
if dirpath.lower().endswith(word.lower()):
dirpath=dirpath[:-(len(word)+1)]
Upvotes: 0
Reputation: 1375
Use the regular expression module 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
Upvotes: 0