[Tutor] Read from large text file, parse, find string, print string + line number to second text file.

Nick W pacificmorrowind at gmail.com
Fri Feb 1 21:31:07 CET 2013

quite easy to do; just use enumerate - as so:
myString = "The String"
with open('largeFile', 'r') as inF:
    for index, line in enumerate(inF):
        #myString = "The String" ##Not here because otherwise this gets run
for every single line of the large file (which is nasty waste of resources)
        if 'myString' in line:
            with open(thenewfile', 'w') as f:
                f.write("Line #%d has string: %s"  (index, line))
That will print the whole line into the new file, If you only want the
characters before that use find and take a slice of the line instead.

On Fri, Feb 1, 2013 at 12:09 PM, Scurvy Scott <etanes.rm at gmail.com> wrote:

> Hey all how're things?
> I'm hoping for some guidance on a problem I'm trying to work through.
> I know this has been previously covered on this list but I'm hoping it
> won't bother you guys to run through it again.
> My basic program I'm attempting to create is like this..
> I want to read from a large, very large file.
> I want to find a certain string
> if it finds the string I would like to select the first 15-20
> characters pre and proceeding the string and then output that new
> string to a new file along with the line the string was located on
> within the file.
> It seems fairly straight forward but I'm wondering if y'all can point
> me to a direction that would help me accomplish this..
> Firstly I know I can read a file and search for the string with (a
> portion of this code was found on stackoverflow and is not mine and
> some of it is my own)
> with open('largeFile', 'r') as inF:
>     for line in inF:
>         myString = "The String"
>         if 'myString' in line:
>             f = open(thenewfile', 'w')
>             f.write(myString)
>             f.close()
> I guess what I'm looking for then is tips on A)My stated goal of also
> writing the 15-20 characters before and after myString to the new file
> and
> B)finding the line number and writing that to the file as well.
> Any information you can give me or pointers would be awesome, thanks in
> advance.
> I'm on Ubuntu 12.10 running LXDE and working with Python 2.7
> Scott
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130201/bab74e60/attachment.html>

More information about the Tutor mailing list