Python problem

J

John Parker

Hi All,

I'm trying to figure out a problem in which I have a file named scores.txt
that contains the following information.


Jane Doe,87,92,97,33
John Doe,78,91,84,25
Bill Gates,91,88,89,56
Bruce Perens,88,92,84,99


I'm wanting to read the file and create two lists: names and scores.

I also want to define a function to calculate the average score for each and
append to a variable called average.

Then call the function and then append to the list scores.

I have my algorithm here:

Define function calcAve(mylist)
Set total = 0
Set count = 0
For i going from 0 to length of mylist
If i is even
total = total + float(mylist)
count = count + 1
Return total/count

Open "scores.txt" for reading, store handle as infile
Read all lines from infile, store as list called lines
Close infile
Create empty lists: names, averages
For each line in lines
Split line using a ",", store as tokens
Append tokens[0] to names
Create empty list called scores
For i going from 1 to length of tokens
Append tokens to scores
Call calcAve(scores), store result as average
Append average to averages
For i going from 0 to length of names
Print names,"scores:",averages


I have written the following code so far but get an error.

infile = open("scores.txt", "r")
lines = infile.readlines()
infile.close()
tokens = lines.split(",")
names = []
scores = []

print lines


for line in lines:
tokens = line.split(",")
if (tokens[0]):
name.append(tokens[0].strip())
elif (tokens in[1,2,3,4]):
scores.append(tokens[1,2,3,4].strip())

error:
Traceback (most recent call last):
File "Score_8.py", line 38, in <module>
tokens = lines.split(",")
AttributeError: 'list' object has no attribute 'split'

So, what am I doing wrong?

Thanks,

John
 
P

Peter Pearson

I have written the following code so far but get an error.

infile = open("scores.txt", "r")
lines = infile.readlines()
infile.close()
tokens = lines.split(",")
[snip]

error:
Traceback (most recent call last):
File "Score_8.py", line 38, in <module>
tokens = lines.split(",")
AttributeError: 'list' object has no attribute 'split'

So, what am I doing wrong?

infile.readlines returns a list of strings, each string being
one line of the input file. Being a list, it doesn't have
a "split" attribute. Strings have a "split" attribute.

Did you intend to split just one of the input strings?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top