[Tutor] Suggestions as to how to read a file in paragraphs

Kent Johnson kent_johnson at skillsoft.com
Wed Sep 1 15:30:12 CEST 2004


You could read the file by lines and accumulate lines in a list until you 
find a paragraph break. Then look at the accumulated lines and see if you 
want to print it. Something like this (assuming a blank line is a paragraph 
break):

     linesInPara = []

     for line in f:
         if not line.strip():
             processParagraph(linesInPara)
             linesInPara = []
         else:
             linesInPara.append(line)

     if linesInPara:
         processParagraph(linesInPara)


At 02:52 PM 9/1/2004 +0200, Tzu-Ming Chern wrote:

>Dear Python tutors,
>
>What is a more efficient way to read a file and split it into paragraphs
>and just print those paragraphs which match a particular condition?
>
>The inefficient way is to read the whole file into one string and then
>split it, but this becomes problematic with larger files. Any suggestions
>on a more efficient approach or is there a module available?
>
>Cheers,
>tzuming
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list