Tuesday, November 16, 2021

Inspired Python: Python Pattern Matching Examples: Working with Paths and Files

Python Pattern Matching Examples: Working with Paths and Files

Manipulating file and path strings is dreary work. It is a common activity, particularly in data science where the file structure may contain important semantic clues like a date or the source of the data. Contextualizing that information is usually done with a mixture of if statements and liberal use of pathlib’s Path or os.path, but the structural pattern matching feature in Python 3.10 is there to cut down on the tedium.

Consider a directory structure that looks a bit like this:

cpi/<country>/by-month/<yyyy-mm-dd>/<filename>.<ext>
cpi/<country>/by-quarter/<yyyy-qq>/<filename>.<ext>

Where cpi means Consumer Price Index; country is the ISO-3166 code for a country; yyyy-mm-dd is the ISO date for the particular month; yyyy-qq is the year and quarter; and filename is an arbitrary filename and ext is an extension.

Ordinarily, you’d just split the path and write some quick logic that picks out what you need, and that’ll work fine for simple things, but if you have to deal with dozens of variadic fields in the file path, that approach will not scale. So let’s look at a way that will scale using the match and case keywords.



Read More ->

from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...