[Tutor] Iterating Lines in File and Export Results

John Doe dantheman5457 at gmail.com
Thu Oct 2 17:47:44 CEST 2014


Hello List,
I am in need of your assistance. I have a text file with random words
in it. I want to write all the lines to a new file. Additionally, I am
using Python 2.7 on Ubuntu 12.04:

Here is my code:

def loop_extract():
    with open('words.txt', 'r') as f:
        for lines in f:
            #print lines (I confirmed that each line is successfully printed)
            with open('export.txt', 'w') as outf:
                outf.write(lines)
                #outf.write(lines)
                #outf.write('{}\n'.format(lines))
                #outf.write('{}\n'.format(line for line in lines))


For some reason, the second file only contains the last line from the
original file -- I have tried multiple variations (.read, .readlines,
.writelines, other examples preceded by comment from above and many
more) and tried to use the module, fileinput, but I still get the same
results.

I do understand there is another way to copy the file over, but to
provide additional background information on my purpose -- I want to
read a file and save successful regex matches to a file; exporting
specific data. There doesn't appear to be anything wrong with my
expression as it prints the expected results without failure. I then
decided to just write the export function by itself in its basic form,
per the code above, which the same behavior occurred; only copying the
last line. I've googled for hours and, unfortunately, at loss.

Thank you in advance for your help!


More information about the Tutor mailing list