[Tutor] File handling Tab separated files

Alan Gauld alan.gauld at yahoo.co.uk
Thu Apr 19 16:59:52 EDT 2018


On 19/04/18 17:50, Niharika Jakhar wrote:
> Hi again
> I tried re-writing the code with all your advices(i assume to cover all of
> them). I have extended the code a little bit to store the data in the form
> of lists and am trying to access it.
> I also changed the file name to BioGRID.txt
> 
> Here's what I wrote(Please ignore the identation, there was no such error,
> it's just the e-mail thingy.):
> 
> import csv
> class BioGRIDReader:
>     def __init__(self, filename):
>         with open('filename', 'rb') as f:

Notice 'filename' is in quotes which means its a literal string
so Python looks for a file called 'filename'. It can't find one.
You really want to use the file name stored in the variable
called filename so remove the quotes. You need to review the
difference between variable names and string literals.

>             self.reader = csv.reader(f, delimiter='\t')
>             self.object_ = self.reader.split['\n']
>             for row in range(len(object_)):
>                 for r in range(len(row)):

This is almost certainly wrong.
The first for sets row to be a number in the range(len...)
The second for line tries to iterate over the len(row)
which will be a very small number - and hence have
no len() value.

>                     if (r[-1] == r[-2]):

And this is probably wrong too even if r from the
line above was to be a small integer. You can't index
an integer.

Now can you express what you really want to do?

I suspect something like:

for row in self.object:    # or self.object.split() maybe?
    if row[-1] == row[-2]  # last two chars are the same
       return row[2],row[3]   # 3rd and 4th chars

HTH

-- 
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