Python: Deleting specific words from a file.

MRAB python at mrabarnett.plus.com
Fri Sep 9 03:31:23 CEST 2011


On 09/09/2011 02:09, papu wrote:
> Hello, I have a data file (un-structed messy file) from which I have
> to scrub specific list of words (delete words).
>
> Here is what I am doing but with no result:
>
> infile = "messy_data_file.txt"
> outfile = "cleaned_file.txt"
>
> delete_list = ["word_1","word_2"....,"word_n"]
> new_file = []
> fin=open(infile,"")
> fout = open(outfile,"w+")
> for line in fin:
>      for word in delete_list:
>          line.replace(word, "")
>      fout.write(line)
> fin.close()
> fout.close()
>
> I have put the code above in a file. When I execute it, I dont see the
> result file. I am not sure what the error is. Please let me know what
> I am doing wrong.

The .replace method _returns_ its result.

Strings are immutable, they can't be changed in-place.



More information about the Python-list mailing list