Take the 2-minute tour ×

I have a text file with two lines in a text file:


Thats the only thing in the text file. Using python, I want to write to the text file so that i can take away BLAHBLAH and FOOFOO from each line. It seems like a simple task but after refreshing my file manipulation i cant seem to find a way to do it. Help is greatly appreciated :)


share|improve this question
Is the file really XML? Or HTML? Or XHTML? If so, please update the question to be more specific on what the file really looks like. There are simple ways to do this if the file matches any of the standards. –  S.Lott Aug 30 '11 at 22:20
Can you show us at least what have you tried yet? –  utdemir Aug 30 '11 at 22:21
add comment

3 Answers

If it's a text file as you say, and not HTML/XML/something else, just use replace:

for line in infile.readlines():
    cleaned_line = line.replace("BLAHBLAH","")
    cleaned_line = cleaned_line.replace("FOOFOO","")

and write cleaned_line to an output file.

share|improve this answer
add comment
f = open(path_to_file, "w+")


Update (saving to another file):

f = open(path_to_input_file, "r")
output = open(path_to_output_file, "w")

share|improve this answer
This way, you append the corrected data to the already existing file. –  glglgl Aug 30 '11 at 23:12
In addition to glglgl, I generally consider it pretty poor form to overwrite the input file unless it's absolutely necessary. What if there's a bug somewhere in your program? –  jozzas Aug 30 '11 at 23:13
add comment

Consider the regular expressions module re.

result_text = re.sub('<(.|\n)*?>',replacement_text,source_text)

The strings within < and > are identified. It is non-greedy, ie it will accept a substring of the least possible length. For example if you have "<1> text <2> more text", a greedy parser would take in "<1> text <2>", but a non-greedy parser takes in "<1>" and "<2>".

And of course, your replacement_text would be '' and source_text would be each line from the file.

share|improve this answer
add comment

Your Answer


