3

I have a text file which has quotations in the form ' and ". This text file is of the form.

"string1", "string2", 'string3', 'string4', ''string5'', etc. 

How can I remove all of the quotations ' and " while leaving the rest of the file the way it is now?

I suspect it should be something like this:

with open('input.txt', 'r') as f, open('output.txt', 'w') as fo:
    for line in f:
        fo.write(line.strip())

Where line.strip() somehow strips the strings of the quotation marks. Is anything else required?

ShanZhengYang
  • 16,511
  • 49
  • 132
  • 234
  • I'd use a generator expression to filter out the quotes instead: `''.join(c for c in line if c not in '"\'')` – Christian Dean Dec 06 '16 at 17:02
  • 1
    Possible duplicate: http://stackoverflow.com/questions/22187233/how-to-delete-all-instances-of-a-character-in-a-string-in-python ShanZhengYang, if that answers your question, let us know. – Robᵩ Dec 06 '16 at 17:03
  • 2
    You could use `replace()` but I wonder how these quotations marks got here. I hope you're not writing out python objects to text files, you should use `pickle` or similar instead – Chris_Rands Dec 06 '16 at 17:04
  • @Robᵩ The problem with `replace()` is that as implemented below, it also removes parentheses – ShanZhengYang Dec 06 '16 at 19:47

1 Answers1

9

You're close. Instead of str.strip(), try str.replace():

with open('input.txt', 'r') as f, open('output.txt', 'w') as fo:
    for line in f:
        fo.write(line.replace('"', '').replace("'", ""))
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • With all due respect, @ShanZhengYang, I don't believe you. Nothing in the code I posted removes parentheses. – Robᵩ Dec 06 '16 at 19:54
  • Looking through the text file, I unfortunately did make a mistake. Deleted above. The parentheses are still there. However, there are several quotations that still exist, especially nearby parentheses `("string1", "string2", "string3", "string4")` – ShanZhengYang Dec 06 '16 at 20:14
  • Again, respectfully, I don't believe you. Can you provide a one-line `input.txt` file that, when handed to the 3-line program above, behaves that way? – Robᵩ Dec 06 '16 at 20:17
  • For this behavior, it's probably best to see the entire text file. – ShanZhengYang Dec 07 '16 at 16:59