Discussion:
[Tutor] readline() problem
Ron Alvarado
2004-02-11 22:25:18 UTC
Permalink
Here's what I'm getting when I try readline(). What an I doing wrong?
data = open('bData.csv', 'r')
num = True
data = data.readline()
print data


Part number Description Item Cost 1104 1105 1118


Traceback (most recent call last):
File "<pyshell#7>", line 2, in -toplevel-
data = data.readline()
AttributeError: 'str' object has no attribute 'readline'
hcohen2
2004-02-11 22:28:50 UTC
Permalink
Post by Ron Alvarado
Here's what I'm getting when I try readline(). What an I doing wrong?
data = open('bData.csv', 'r')
num = True
data = data.readline()
print data
When you openned the file, data was the file handle which you have
confused it with a string value of the same name. Since data types are
dynamic in Python your file handle value is lost.

try

str_data = data.readline()
print str_data

both that line and the print should be to the right of the 'while ...'
Post by Ron Alvarado
Part number Description Item Cost 1104 1105 1118
File "<pyshell#7>", line 2, in -toplevel-
data = data.readline()
AttributeError: 'str' object has no attribute 'readline'
_______________________________________________
http://mail.python.org/mailman/listinfo/tutor
Marilyn Davis
2004-02-11 22:33:49 UTC
Permalink
Post by Ron Alvarado
Here's what I'm getting when I try readline(). What an I doing wrong?
data = open('bData.csv', 'r')
num = True
data = data.readline()
print data
The first call to data.readline() will read the first line of the
file, make a string of it, and then rename 'data' to be that
string/line.
Karl Pflästerer
2004-02-11 22:37:59 UTC
Permalink
Post by Ron Alvarado
Here's what I'm getting when I try readline(). What an I doing wrong?
data = open('bData.csv', 'r')
num = True
data = data.readline()
print data
Part number Description Item Cost 1104 1105 1118
File "<pyshell#7>", line 2, in -toplevel-
data = data.readline()
AttributeError: 'str' object has no attribute 'readline'
Several things here are wrong.
(a) You have an endless loop (or do you set num somewhere in your code)
(b) First data is file object; then you assign to data (the same name!)
the value of date.readline() which is a string. data gets printed
and the second calls causes this error (since data is now a string).
(c) Nowadays there is a better idiom in Python to iterate over the lines
of a file: for var in file: ....

So your code could be written as:

data = file('bData.csv')

for line in data:
print line


Karl
--
Please do *not* send copies of replies to me.
I read the list
Loading...