Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
9.10. Parsing lines
Usually when we are reading a file we want to do something to the lines
other than just printing the whole line. Often we want to find the
“interesting lines” and then parse the line to find
some interesting part of the line. What if we wanted to print out the
day of the week from those lines that start with “From “?
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
The split
method is very effective when faced with this
kind of problem. We can write a small program that looks for lines where
the line starts with “From “, split
those lines, and then
print out the third word in the line:
Later, we will learn increasingly sophisticated techniques for picking
the lines to work on and how we pull those lines apart to find the exact
bit of information we are looking for.
The following code should open a file and read through the lines, splitting them when a line starts
with “Hello”, then printing the second word in the line. Watch out for extra pieces of code and
indentation.
fhand = open('myFile.txt')
---
for line in fhand:
---
for line in myFile: #distractor
---
line = line.rstrip() #remove trailing whitespace
---
if not line.startswith('From '): continue #distractor
---
if not line.startswith('Hello'): continue
---
words = line.split()
---
print(words[1])
---
print(words[2]) #distractor
You have attempted
of
activities on this page