[Tutor] implementing a table data structure in python?

Kent Johnson kent37 at tds.net
Tue Dec 21 16:59:49 CET 2004


Juan Shen wrote:
>    My python code:
> #!/usr/bin/python
> #Filename: selectcolumn.py
> import sys
> datafile='mydata' #Your datafile
> columns=[1,2,3,5] #Columns which you'd like to print
> try:
>    f=open(datafile)
> except IOError:
>    print "Can't open data file."
>    sys.exit()
> for line in list(f):
>    data=line.split()
>    try:
>        data=[data[i] for i in columns]

(Sound of smacking forehead with hand)
Thanks! I knew there had to be a better way than what I wrote!

Kent

>    except IndexError:
>        print 'Column index out of range.'
>        f.close()
>        sys.exit()
>    print '\t'.join(data)
> f.close()
>  


More information about the Tutor mailing list