Search-and-delete text processing problem...

M.E.Farmer mefjr75 at hotmail.com
Fri Apr 1 21:18:09 EST 2005


Strings have many methods that are worth learning.
If you haven't already discovered dir(str) try it.
Also I am not sure if you were just typing in some pseudocode, but your
use of writelines is incorrect.
help(file.writelines)
Help on built-in function writelines:

writelines(...)
    writelines(sequence_of_strings) -> None.  Write the strings to the
file.

    Note that newlines are not added.  The sequence can be any iterable
object
    producing strings. This is equivalent to calling write() for each
string.

Todd_Calhoun wrote:
> I'm trying to learn about text processing in Python, and I'm trying
to
> tackle what should be a simple task.
>
> I have long text files of books with a citation between each
paragraph,
> which might be like "Bill D. Smith, History through the Ages, p.5".
>
> So, I need to search for every line that starts with a certain string
(in
> this example, "Bill D. Smith"), and delete the whole line.
>
> I've tried a couple of different things, but none seem to work.
Here's my
> latest try.  I apologize in advance for being so clueless.
>

##########################
#Text search and delete line tool
theInFile = open("test_f.txt", "r")
theOutFile = open("test_f_out.txt", "w")
allLines = theInFile.readlines()
theInFile.close()

for line in allLines:
    if not line.startswith('Bill'):
        theOutFile.write(line)

theOutFile.close()
#########################

# You can also accumulate lines
# in a list then write them all at once
##########################
#Text search and delete line tool
theInFile = open("test_f.txt", "r")
theOutFile = open("test_f_out.txt", "w")
allLines = theInFile.readlines()
theInFile.close()

outLines = []

for line in allLines:
    if not line.startswith('Bill'):
        outLines.append(line)

theOutFile.writelines(outLines)
theOutFile.close()
#########################

hth,
M.E.Farmer




More information about the Python-list mailing list