Fwd: Python new user question - file writeline error

Shawn Milo Shawn at Milochik.com
Thu Feb 8 10:41:44 EST 2007


To the list:

I have come up with something that's working fine. However, I'm fairly
new to Python, so I'd really appreciate any suggestions on how this
can be made more Pythonic.

Thanks,
Shawn






Okay, here's what I have come up with:


#! /usr/bin/python

import sys
import re

month ={'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG':8,'SEP':9,'OCT':10,'NOV':11,'DEC':12}
infile=file('TVA-0316','r')
outfile=file('tmp.out','w')

def formatDatePart(x):
        "take a number and transform it into a two-character string,
zero padded"
        x = str(x)
        while len(x) < 2:
                x = "0" + x
        return x

regex = re.compile(r",\d{2}/[A-Z]{3}/\d{4},")

for line in infile:
        matches = regex.findall(line)
        for someDate in matches:

                dayNum = formatDatePart(someDate[1:3])
                monthNum = formatDatePart(month[someDate[4:7]])
                yearNum = formatDatePart(someDate[8:12])

                newDate = ",%s-%s-%s," % (yearNum,monthNum,dayNum)
                line = line.replace(someDate, newDate)

        outfile.writelines(line)

infile.close
outfile.close



More information about the Python-list mailing list