[Tutor] Import multiple lines of text into a variable

Steven D'Aprano steve at pearwood.info
Tue Apr 12 13:58:33 CEST 2011


Sean Carolan wrote:
>>> if line.startswith('notes'):
>>>   break
>>> notes = open('myfile','r').read().split(notes:\n')[1]
>> The first two lines are redundant you only need the last one.
> 
> I should have clarified, the "if line.startswith" part was used to
> break out of the previous for loop, which was used to import the
> other, shorter strings.


Just for reference, "import" has special meaning in Python, and you hurt 
my brain by using it as a synonym for "read".

For what it's worth, here's my solution. Rather than use the funky new 
"open files are iterable" feature, go back to the old-style way of 
reading line by line:

# untested
fp = open("myfile.txt")
for while True:
     line = fp.readline()  # read one line
     if not line:
         # nothing left to read
         break
     if "ham" in line:
         process_ham(line)  # Mmmm, processed ham...
     if "spam" in line:
         process_spam(line)
     if line.startswith("notes"):
         notes = fp.read()  # reads the rest of the file
fp.close()


Note that it is okay to mix calls to read() and readline(), but it is 
NOT okay to mix iteration over a file with calls to read() or readline().




-- 
Steven


More information about the Tutor mailing list