0

I'm trying to replace some characters in a textfile.

Code:

import easygui

textfile = easygui.enterbox(msg='File:') # only used for input
f1 = open(textfile, 'r')
f2 = open(textfile, 'w')
for line in f1:
    f2.write(line.replace('a', '-apple-')), # also tried without comma; same result
    f2.write(line.replace('t', '-tree-'))   
f1.close()
f2.close()

File:

this is a test!

But the output is messed up and instead of replace the letters in one go, the script creates multiple sentences in the file like:

this is -apple- test!-tree-his is a -tree-es-tree-!

Is it even possible to replace multiple letters in only one line?

hapstyx
  • 37
  • 4
  • 2
    *Think about what you're doing*; you're writing the same line to the file twice, with different parts replaced! – jonrsharpe Oct 06 '15 at 14:44
  • @jonrsharpe So how should I do it? – hapstyx Oct 06 '15 at 14:47
  • 1
    Split the problem into smaller parts - can you write a function that will take a single line and return it with all of the replacements carried out, for example? That's much easier to test without the round trips to files. In short: learn to program! – jonrsharpe Oct 06 '15 at 14:48

0 Answers0