I am creating the following dataframe and then writing it to a txt file:
df = pd.DataFrame({'key': ['0001'], 'name': ['"LUCA"']})
df.to_csv('names.txt', index=False)
I expect my txt file to look like this:
key,name
0001,"LUCA"
But it is looking like this instead:
key,name
0001,"""LUCA"""
Any suggestion please?
CodePudding user response:
You can change the quotechar
in to_csv
to avoid interpreting "
as the quoting character:
df = pd.DataFrame({'key': ['0001'], 'name': ['"LUCA"']})
df.to_csv('names.txt', index=False, quotechar="'")
output file:
key,name
0001,"LUCA"
This means, however, that if you really need escaping, you will have single quotes:
df = pd.DataFrame({'key': ['0001', '0002'], 'name': ['"LUCA"', 'LUCA,']})
df.to_csv('names.txt', index=False, quotechar="'")
output:
key,name
0001,"LUCA"
0002,'LUCA,'