[Tutor] File handling Tab separated files

Alan Gauld alan.gauld at yahoo.co.uk
Fri Apr 20 05:06:56 EDT 2018


Use Reply-All or Reply-List to include the mailing list in replies.

On 20/04/18 09:10, Niharika Jakhar wrote:
> Hi
>
> I want to store the data of file into a data structure which has 11
> objects per line , something like this:
> 2354   <tab>      somethin2     <tab> 23nothing   <tab>    23214.....
>
>
> so I was trying to split the lines using \n and storer each line in a
> list so I have a list of 11 objects, then I need to retrieve the last
> two position,

You are using the csv module so you don't need to split the lines, the
csv reader has already done that for you. It generates a sequence of
tuples, one per line.

So you only need to do something like:

results = []
with open(filename) as f:
     for line in csv.reader(f, delimiter='\t'):
         if line[-1] == line[-2]:
            results.append(line[2],line[3])

Let the library do the work.

You can see what the reader is doing by inserting a print(line) call
instead of the if statement. When using a module for the first time
don't be afraid to use print to check the input/output values.
Its better than guessing.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list