Processing file names

I seem to have spent a lot of time working with files this month. My task today was summarise the output from an inventory tool. This tool (well vb script) had created a lot of text files with the computer name and a date serial in the name. What I wanted is this information in a CSV file to compare to our asset list.

There are lots of ways of doing this but as the computer name is variable length but otherwise the file is known I used a regular expression. Regular expressions can get complicated but it this case I’m just looking for any letter, number, underscore or dash followed by .example.com (for my computer name) then an underscore followed by a 12 digit datetime serial. The rest of the name is irrelevant.

I am also using grouping by enclosing the computer name and datetime serial in parentheses. This allows me to return the matched details using group().

For the code below to work you would need to define a function formatdate to turn the datetime serial into something more readable. I’ve left this out to improve the clarity of the example.

import os, re, csv
prog = re.compile(r"([a-zA-Z0-9_\-]+).example.com_([0-9]{12})")

def getinfo ( instr ):
    res = prog.match(instr)
    if res:
        return (res.group(1),formatdate(res.group(2))]

with open('names.csv','w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(['Computer','Date']) # header
    for file in os.listdir(r'\\server\path\to\inventories'):
        fileinfo = getinfo(file)
        if fileinfo:
            csvwriter.writerow(fileinfo)

The natural progression would be to list comprehension to create a list and then write this all out in one go using writerows instead. However getting this to handle cases where the match failed resulted in code ugly code. If I work a way around this I’ll include it.

If you needed to include sub-directories as well then you could use os.walk instead of os.listdir then loop of the files list returned.

Published by Quackajack

I started off as a programmer, who moved to support (setting up 2 service desks from scratch), then on to system administrator and then into configuration management. Now I combined all these as a DevOps engineer.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.