[Tutor] Simple Regex
dn
PyTutor at DancesWithMice.info
Thu Apr 8 16:40:09 EDT 2021
On 09/04/2021 08.26, Alan Gauld via Tutor wrote:
> 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.
Per earlier comments, this is where previous-experience takes me too.
Alternatively (following earlier web.ref), could use the 'common factor'
approach to remove the "C:\Users\user\Downloads\" constant-component
from view, and os.path.split() from there.
--
Regards,
=dn
More information about the Tutor
mailing list