extract substring by regex from a text file

Discussion in 'Python' started by Alessio, Apr 15, 2010.

  1. Alessio

    Alessio Guest


    I'm facing the problem in the subject:
    - I have a text file that I need to parse for producing a specifical
    string (Json like) extracting some information (substring) in it;
    - I created regural expressions capable to locate these substrings in
    my txt file;

    now I don't know how to continue. What is the best way to locate some
    string in a file and output them (with print command or in another

    Thx in advance
    Alessio, Apr 15, 2010
    1. Advertisements

  2. Alessio

    Neil Cerutti Guest


    Or: show your work.
    Neil Cerutti, Apr 15, 2010
    1. Advertisements

  3. Alessio

    Alessio Guest

    Thank you, I forgot to say that I already solved.
    I used readlines() to read my text file, then with a for cicle I
    extract line by line the substrings I need by regular expressions

    Alessio, Apr 17, 2010
  4. Alessio, 17.04.2010 10:19:
    Note that it's usually more efficient to just run the for-loop over the
    file object, rather than using readlines() first. The latter will read all
    lines into a big list in memory before doing any further processing,
    whereas the plain for-loop will read line by line and let the loop body act
    on each line immediately.

    Stefan Behnel, Apr 17, 2010
  5. Alessio

    Peter Otten Guest

    Just in case you didn't know:

    for line in instream:

    looks better, uses less memory, and may be a tad faster than

    for line in instream.readlines():

    Peter Otten, Apr 17, 2010
  6. Alessio

    Alessio Guest

    Thanks for your suggestions, they are welcome... I'm at the beginning
    with python.
    I just changed my script to parse the file without readlines()
    Alessio, Apr 17, 2010
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.