1

I need to write a text file, line by line. This code is printing a text line by line, but only the last line is stored in the result.txt file.

import re
import fileinput
for line in fileinput.input("test.txt"):
    new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
    print new_str
open('result.txt', 'w').write(new_str)
msw
  • 42,753
  • 9
  • 87
  • 112
Dhilip Kumar
  • 29
  • 1
  • 2
  • 6
  • Looks like you want to open the file first (before the loop) and then write data to it on each iteration through the loop (f=open(...) ... then later f.write(new_str)) – Jim Dennis Aug 17 '13 at 10:34

3 Answers3

5
  1. I don't know why you need the fileinput module, open can handle this case as well.

  2. Your for-loop goes through all lines and overrides new_str with the new line. The last line has no next line, so it won't be overridden, so it's the only line that will get saved.

    import re
    test_f = open('test.txt')
    result_f = open('result.txt', 'a')
    for line in test_f:
        new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
        result_f.write(new_str)
    
    # also, this too, please:
    test_f.close()
    result_f.close()
    
  3. You should use the with statement to automatically close your files even when your code crashes.

    import re
    with open('test.txt') as test_f, open('result.txt', 'w') as result_f:
        for line in test_f:
            new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
            result_f.write(new_str)
    
Eric
  • 95,302
  • 53
  • 242
  • 374
Markus Unterwaditzer
  • 7,992
  • 32
  • 60
0

You have print new_str for every line in test.txt. But you only write one line to the file after the loop. Changing the code to write after each print:

outf = open('result.txt', 'w')
for line in fileinput.input("test.txt"):
    new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
    print new_str
    outf.write(new_str + '\n')
outf.close()

will do what you want.

msw
  • 42,753
  • 9
  • 87
  • 112
  • The other thing to note is the `re.sub` is replacing `\n` with `' '`... so even with the `outf.write` in the correct place it's going to look like one big line... – Jon Clements Aug 17 '13 at 10:33
  • @JonClements agreed, cheezy fix added. – msw Aug 17 '13 at 11:17
0

I assume you need to add new lines at the end of the file (i.e append)

for line in fileinput.input("test.txt"):
new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
with open("f.txt", "a") as f:
f.write(new_str)

You can use the f.write line and repeat it until you write everything

Sushruth Siv
  • 45
  • 1
  • 8