help me to find the error

Rhodri James rhodri at wildebst.demon.co.uk
Fri Jul 10 08:22:31 EDT 2009


On Fri, 10 Jul 2009 10:41:03 +0100, jhinak sen <jhinak.sen at gmail.com>  
wrote:

> hi,
> i am a beginner in python language,
>
> i am trying with this programme :
> to find the addition and mean from a data set in a file and writing the  
> mean
> and sum in some other file :
> ""
> *#! /usr/bin/env python
>
> import re
> import cPickle as p
> import math
> from numpy import *
>
> f0= open("temp9","r+").readlines()
> f2= open("out1","r+")
> add_1=[ ];
> for i in range(0, len(f0)):
>         f1=f0[i].split()
>         add= float(f1[1])+float(f1[2])
>     mean= float(add)/2
>         print (f1[1]).ljust(6) ,(f1[2]).ljust(6),repr(add).ljust(7),
> repr(mean).ljust(7)
>         add_1.append(add)
>     add_1.append(mean)
>         f2.write("%s" % repr(add).ljust(7)),f2.write("%s" %
> repr(mean).ljust(7))
> print "printing from file"
> for i in range(0, len(add_1),2):
>         print add_1[i],"        ", add_1[i+1]
>
> f0.close()
> f2.close()*
>
>
> ""
>
> and this programme is givving me this error :
>
> ""    *Traceback (most recent call last):
>   File "./temporary1.py", line 24, in <module>
>     f0.close()
> AttributeError: 'list' object has no attribute 'close'*
> ""

As the error message tells you, 'f0' is a list.  readlines()
returns a list of the lines in the file object, rather than the
file object itself.  Since you promptly (and entirely reasonably)
discard the file object, you haven't got any way to close() it.

You don't actually need to do that, though.  You can use a file
object as something you use a 'for' loop over, and be given one
line at a time.  So instead you can write your code like this:

<snippet>
f0 = open("temp9", "r")
for line in f0:
     f1 = line.split()
     # ... and so on
</snippet>

Notice that I only opened the file as "r" -- you are only
reading it, not updating it, and giving yourself more permission
than you need is a bad habit to get into.  Opening the file this
way means that if you accidentally write f0.write("something")
instead of "f2.write(something)", Python will stop you with an
exception rather than silently trash your data.

-- 
Rhodri James *-* Wildebeest Herder to the Masses



More information about the Python-list mailing list