[Tutor] reading complex data types from text file
Chris Castillo
ctcast at gmail.com
Thu Jul 16 20:20:01 CEST 2009
*so far I have this and the format is what i want:*
------------------------------------------------------------------------------------------
# Set all necessary variables
name = None
fileOut = open('outputFile.txt', 'w')
total = 0
averageScore = 0
numofScores = 0
score = 0
# Header for output file
fileOut.write("Bowling Report\n" + ("-" * 40) + "\n")
# Iterate line by line through file to get names and their corresponding
scores
for line in open('bowlingscores.txt', 'r'):
line = line.strip()
if line:
if line.isdigit():
score = int(line)
numofScores += 1
total += score
averageScore = total / numofScores # Get average score
# Decides where bowler stands compared to the average score
if score < averageScore:
score = "\tBelow average"
elif score > averageScore and score != 300:
score = "\tAbove average!"
elif score == 300:
score = "\tPerfect score!"
else:
name = line
# Checks to see if name and score have values
if name and score:
fileOut.write('%s\t%s\r\n' % (name, score))
name, score = None, None
fileOut.close()
------------------------------------------------------------------------------------
*the problem is that it's not comparing the first bowler's score to the
average score and the output file looks like this:
*
Bowling Report
----------------------------------------
David 120
Hector Perfect score!
Mary Below average
*
is the logic in my if-elif statements wrong or is it just skipping the first
bowler's score?
*
On Thu, Jul 16, 2009 at 8:26 AM, Glen Zangirolami <digitalman66 at gmail.com>wrote:
> All lines that come back from a text file come back as strings. You can use
> string methods to detect the data like so:
> f = open('test.txt')
> lines = f.readlines()
> numbers = []
> strings = []
>
> for line in lines:
> if line.strip().isdigit():
> numbers.append(int(line))
> else:
> strings.append(line.strip())
>
> print numbers
> print strings
>
>
>
> On Wed, Jul 15, 2009 at 1:55 PM, Chris Castillo <ctcast at gmail.com> wrote:
>
>> I'm having some trouble reading multiple data types from a single text
>> file.
>>
>> say I had a file with names and numbers:
>>
>> bob
>> 100
>> sue
>> 250
>> jim
>> 300
>>
>> I have a few problems. I know how to convert the lines into an integer but
>> I don't know how to iterate through all the lines and just get the integers
>> and store them or iterate through the lines and just get the names and store
>> them.
>>
>> please help.
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090716/e77a0c5b/attachment-0001.htm>
More information about the Tutor
mailing list