[Tutor] .txt matrix import

Dave Angel davea at davea.name
Thu Aug 8 01:28:11 CEST 2013


Joshua Kim wrote:

> Hello, 
>
> This is my first time using Tutor, so I apologize for any fallacies I may be making; my problem involves opening a .txt file which contains several lines of descriptive information followed by a tab delimited matrix of numerical values… I am trying to find an effective way in which to skip the first 'X' number of lines in the .txt file (54 in my case) and input the columns of data into individual arrays (note the 55th line denotes the title of the column, so preferably I would like to have python use those values as the names to the individual array, but I am unsure of how involved that may become)
>
>
> Any hints/suggestions/pointers would be appreciated. 
>

First, let me suggest you not send html mail.  It basically tripled the
size of your message, and many times it will also distort parts of your
message, especially when you're including code.

Your query basically says you have a file that's in two parts.  The
first part is to be ignored, and the second part is a simple csv file,
complete with column headings.

All you need do to skip the first part is to call readline() on the file
object X times, something like:

    for temp in range(X):
        infile.readline()

At this point, the infile object is positioned at the header line of the
csv data.

You can then use the csv module to successively turn each row of the
infile into a dict, with the names being the ones specified in the
file.

This will give you the data organized by row.  I'd recommend you get
this much debugged before trying to convert it to columns.

BTW you may not need the csv module if your data itself never has a tab
in it.  The place where the module really helps is (for example in a
comma-delimited file) when there's sometimes a comma in the actual data
that needs escaping, or quoting.


--
DaveA




More information about the Tutor mailing list