iNoob
iNoob

Reputation: 1395

Reading a filename and applying part of that name to a variable

I am looking to filter files in a directory and then assign part of that filename (the value I am trying to match changes) to a variable. The structure of the filename is consistent with the following example. *test file on part-of-filename-of-interest.csv. The last part of the filename is the part I would like to add to a variable value. So it will always be the last part of the filename and after the word on.

I am able to filter all the files of interest using the below but I am not sure on how to grab the part-of-filename-of-interest section to place it to a variable value.

for root, dirs, files in os.walk('dirpath'):
    filters = '*test file on*.csv'
    for filename in fnmatch.filter(files, filters):
        print filename    #I get all the files im interested in but I dont know how to capture the relevant part of the filename to place it in a variable

Upvotes: 0

Views: 76

Answers (3)

TigerhawkT3
TigerhawkT3

Reputation: 49318

If there's no way to access what you're looking for with fnmatch, the simplest and fastest solution is probably a string method:

print filename.partition('on')[2]

Upvotes: 1

digitaLink
digitaLink

Reputation: 458

Try using regex expressions to match the part you want.

import re
p = re.compile("(?<=on ).+")
filename = "*test file on part-of-filename-of-interest.csv"
new_filename = p.search(filename).group(0)

If you don't want the .csv included change the regex expression to this:

p = re.compile("(?<=on ).+(?=.csv)")

This is a good example of lookahead and lookbehind.

Upvotes: 1

BlivetWidget
BlivetWidget

Reputation: 11063

Depending on the consistency of your pattern, would this work for you?

>>> fn = 'test file on part-of-filename-of-interest.csv'
>>> import os
>>> os.path.splitext(fn[fn.find('test file on') + 13:])[0]
'part-of-filename-of-interest'

Upvotes: 1

Related Questions