[2.5.1] Read each line from txt file, replace, and save?

Discussion in 'Python' started by Gilles, Sep 2, 2012.

  1. Gilles

    Gilles Guest


    This is a newbie question.

    I need to read a text file into a variable, loop through each line and
    use a regex to substitute some items within the line, and save the
    whole variable into a new text file.

    This triggers an error when I save the modified variable that contains
    all the lines:
    import re,sys

    f = open("C:\\input.txt", "r")
    textlines = f.readlines()

    for line in textlines:
    #edit each line
    line = "just a test"

    #rewrite data to new file
    log = open('output.sub','w')
    #ERROR: argument 1 must be string or read-only character buffer, not

    Should I use another way to read the file, edit each line, and save
    the data into a new file?

    Thank you.
    Gilles, Sep 2, 2012
    1. Advertisements

  2. Gilles

    Gilles Guest


    Found it:

    #rewrite lines to new file
    output = open('output.txt','w')

    for line in textlines:
    #edit each line
    line = "just a test"
    output.write("%s" % line)

    Gilles, Sep 2, 2012
    1. Advertisements

  3. Mark Lawrence, Sep 2, 2012
  4. Gilles

    Terry Reedy Guest

    If you process each line separately, there is no reason to read them all
    at once. Use the file as an iterator directly. Since line is already a
    string, there is no reason to copy it into a new string. Combining these
    two changes with Mark's suggestion to use with and we have the following
    simple code:

    with open('input.txt', 'r') as inp, open('output.txt', 'w') as out:
    for line in inp:

    where for your example, process(line) == 'just a test\n'
    (you need explicit line ending for .write())
    Terry Reedy, Sep 2, 2012
  5. Gilles

    Gilles Guest

    Thanks guys for the suggestion.
    Gilles, Sep 5, 2012
    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.