[Tutor] Simple Regex

Alan Gauld alan.gauld at yahoo.co.uk
Thu Apr 8 16:26:05 EDT 2021


On 08/04/2021 18:43, Joao Carlos Silva de Oliveira Matos via Tutor wrote:

> I have to parse a regex for the first time. I have this path:
> *C:\Users\user\Downloads\4324234534254325\4324234534254325_213.csv.*

No you don;t. You should hardly ever need regex to work with paths.
Use the os.path module instead.

> I want to retrieve the name of the folder between "Downloads\" and
> "\filename".

os.path.dirname() removes the filename
os.path.split() returns the first and last parts of a path


So

import os.path

p = r"C:\Users\user\Downloads\4324234534254325\4324234534254325_213.csv"

dir = os.split(os.path.dirname(p))[1]

Should get what you want.

If the number of folders is always the same you could even
use a simple string.split:

dir = p.split('\')[4]

But os.path takes care of path separators on different platforms
so is the preferred solution for portability.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list