Reading a file into a data structure....
Ian Kelly
ian.g.kelly at gmail.com
Thu Oct 13 18:28:24 EDT 2011
On Thu, Oct 13, 2011 at 3:59 PM, MrPink <tdsimpson at gmail.com> wrote:
> This is a continuing to a post I made in August:
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/b072cfadf998deae/ce6d4d09911e4107?lnk=gst&q=MrPink#ce6d4d09911e4107
>
> I got some free time to work with Python again and have some followup
> questions.
>
> For example, I have a list in a text file like this:
> Example list of lottery drawings:
> date,wb,wb,wb,wb,wb,bb
> 4/1/2011,5,1,45,23,27,27
> 5/1/2011,15,23,8,48,22,32
> 6/1/2011,33,49,21,16,34,1
> 7/1/2011,9,3,13,22,45,41
> 8/1/2011,54,1,24,39,35,18
> ....
>
> Ticket:
> startdate,enddate,wb,wb,wb,wb,wb,bb
> 4/1/2011,8/1/2011,5,23,32,21,3,27
>
> I am trying to determine the optimal way to organize the data
> structure of the drawing list, search the drawing list, and mark the
> matches in the drawing list.
>
> f = open("C:\temp\drawinglist.txt", "r")
> lines = f.readlines()
> f.close()
> drawing = lines[1].split()
That looks like a CSV file. If the contents are tightly constrained
then it may not matter, but if not then you should consider using the
csv module to read the lines, which will handle inconvenient details
like quoting and escape characters for you.
> I need to convert drawing[0] to a date datatype. This works, but I'm
> sure there is a better way.
> from datetime import date
> month, day, year = drawing[0].split('/')
> drawing[0] = date(int(year), int(month), int(day))
If you already know the format:
from datetime import datetime
drawing[0] = datetime.strptime(drawing[0], '%m/%d/%Y').date()
If you can't be sure of the format, then I recommend using the
python-dateutil parser.parse() function, which will try to work it out
on the fly.
More information about the Python-list
mailing list