Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to remove all quotations from a text file?

Tags:

python

text

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?

like image 496
ShanZhengYang Avatar asked May 09 '26 12:05

ShanZhengYang


1 Answers

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("'", ""))
like image 173
Robᵩ Avatar answered May 12 '26 04:05

Robᵩ