[Tutor] help with reading a string?
steve at pearwood.info
Mon Jul 16 20:06:49 EDT 2018
Hi Crystal, and welcome! My response is further below, after your
On Mon, Jul 16, 2018 at 05:28:37PM -0500, Crystal Frommert wrote:
> Hi, I am a beginner comp sci teacher at an all-girls high school. The girls
> are learning how to read from a txt file and search for a string.
> Here is a sample of text from the txt file:
> How do they read the number after a certain searched name and then add up
> the numbers after each time the name occurs?
Which version of Python are you using? The answer may depend on the
exact version, but something like this ought to be good:
# Code below is not tested, please forgive any bugs when you try it...
# Process the lines of some text file.
total = 0
with open("path to the file.txt", "r") as f:
# Read the file line-by-line.
for line in f:
# Split each record into five fields.
# Please pick more meaningful field names for a, b, c!
a, b, c, name, score = line.split(",")
# Choose only records for a specific person.
# Here I hard-code the person's name, in practice
# you ought to use a variable.
if name == "Sarah":
# Convert the score from a string to an int,
# and add it to total.
total = total + int(score)
# Dropping back to the extreme left automatically closes
# the file.
Remember that in Python, indentation is not optional.
Some extra features:
* You can re-write the line "total = total + int(score)" using the more
compact notation "total += int(score)"
* Instead of the "with open(...) as f", you can do it like this:
f = open("path to the file.txt") # the "r" parameter is optional
for line in f:
# copy for loop from above to here
# (don't forget to reduce the indentation by one level)
# Explicitly close the file.
f.close() # A common error is to forget the parentheses!
# And finally print the total.
Hope this helps, and please don't hesitate to ask if you have any
questions. Keep your replies on the mailing list so others may
contribute answers and learn from the responses.
More information about the Tutor