Remove part of the path
I have the following data:
/​share/​Downloads/​Videos/​Movies/​Big.Buck.Bunny.​720p.​Bluray.​x264-BLA.​torrent/Big.Buck.Bunny.​720p.​Bluray.​x264-BLA
However, I don't want to have "Big.Buck.Bunny. 720p. Bluray. X264-BLA.torrent /" in it, I want the path to be like this:
/​share/​Downloads/​Videos/​Movies/Big.Buck.Bunny.​720p.​Bluray.​x264-BLA
With regexp, I basically want math that contains * .torrent. /, How can I accomplish this in regexp?
Thank!
source to share
You don't even need regular expressions. You can use os.path.dirname
and os.path.basename
:
os.path.join(os.path.dirname(os.path.dirname(path)),
os.path.basename(path))
where path
is the original path to the file.
Alternatively, you can also use os.path.split
like this:
dirname, filename = os.path.split(path)
os.path.join(os.path.dirname(dirname), filename)
Note. This will work on the assumption that what you want to delete is the directory name that contains the file from the path, as in the example in the question.
source to share
You can do this without using regexp:
>>> x = unicode('/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA.torrent/Big.Buck.Bunny.720p.Bluray.x264-BLA')
>>> x.rfind('.torrent')
66
>>> x[:x.rfind('.torrent')]
u'/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA'
source to share
Considering path='/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA.torrent/Big.Buck.Bunny.720p.Bluray.x264-BLA'
You can do it with regex like
re.sub("/[^/]*\.torrent/","",path)
You can also do it without regex as
'/'.join(x for x in path.split("/") if x.find("torrent") == -1)
source to share
Your question is a bit vague and unclear, but here is one way to reverse what you want:
import re
s = "/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA.torrent/Big.Buck.Bunny.720p.Bluray.x264-BLA"
c = re.compile("(/.*/).*?torrent/(.*)")
m = re.match(c, s)
path = m.group(1)
file = m.group(2)
print path + file
>>> ## working on region in file /usr/tmp/python-215357Ay...
/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA
source to share