File traversing

Chris Angelico rosuav at gmail.com
Sun Apr 15 05:51:03 EDT 2012


On Sun, Apr 15, 2012 at 7:15 PM, Nibin V M <nibinvm at gmail.com> wrote:
> res_own_file = open('/bah')
> res_own_list = res_own_file.readline()
> res_tot_list=[]
> while res_own_list:
>   res_own_list=res_own_list.strip()
>   res_own_list=res_own_list.replace(' ', '')
>   res_name=res_own_list.split(':')
>   if res_name[1:2] not in res_tot_list:
>     res_tot_list.append(res_name[1:2])
>   res_own_list = res_own_file.readline()

You can iterate over the file thus:

for res_own_list in res_own_file:
  # body of loop here

That saves you the trouble of making sure you do the next readline at
the bottom, too.

(You may also want to consider using the 'with' statement to guarantee
a timely closing of the file. Outside the scope of this mail though.)

> As you can see above, I am reading each line, cut a particular field and
> sort a unique list from it...I have two questions here
>
> 1. If I have to check the file again from beginning, I can't do it without
> closing and re-opening file since the file pointer is assigned to the EOF of
> the opened file right? If so, is there any alliterative method to do it? I
> don't wish to mess the script with multiple file open-close code!

You should be able to use res_own_file.seek(0) to do that. I haven't
tested your code, but that ought to work. If it fails, post code that
uses seek and the error message you get, and someone will doubtless
know what's wrong.

> 2. If I print  res_name, it will display like ['one', 'two']. If I
> print  res_name[0], it will display one ; but if I print  res_name[1] it
> will display error out of index instead of two. From my code, when I use
> res_name[1:2] it's displaying second filed. Why it is behaving like this?

My guess here is that at the end of the file, you get a blank line.
When you use [1:2] syntax, you get back an empty list if the indices
are out of bounds; but [1] will throw an error.

if res_name[1:2] not in res_tot_list:
    res_tot_list.append(res_name[1:2])

I think this list is just to collect unique entries, yes? If so, a set
may be more to your liking. Check out:
http://docs.python.org/py3k/library/stdtypes.html#set

Hope that's of some value!

Chris Angelico



More information about the Python-list mailing list