简体   繁体   中英

Handling mixed string with double quotations and numbers to save in csv

I have three lines that I need to save as header of my csv files. They should look like this:

title = "dataset test"
variables = "X", "Y", "Z", "V"
zone t = "Data Field", i = 134, j = 293, k = 5, f=point

I am using the following code to create the pandas dataframe:

info = pd.DataFrame(['title = "dataset test"',
                    'variables = "X", "Y", "Z", "V"',
                    'zone t = "Data Field", i = 134, j = 293, k = 5, f=point'])

And using the following code to write the csv file:

with open(fpath, 'w') as myfile:
        info.to_csv(myfile, header=None, index=False)

However the output in the csv file is as:

"title = ""dataset test"""
"variables = ""X"", ""Y"", ""Z"", ""V"""
"zone t = ""Data Field"", i = 134, j = 293, k = 5, f=point"

Below this header there are three columns of number which will be add afterward; the final output should be like this:

title = "dataset test"
variables = "X", "Y", "Z", "V"
zone t = "Data Field", i = 134, j = 293, k = 5, f=point
6.1961335E+06   2.3218804E+06   1.3564390E+03
6.1961547E+06   2.3218672E+06   1.3473630E+03
6.1961759E+06   2.3218540E+06   1.3382290E+03
6.1961972E+06   2.3218408E+06   1.3322720E+03

which I do it using df.to_csv(myfile, header=None, index=False, sep='\\t',float_format='%.7E')

Have you tried using the \\ escape character on this line

'variables = "X", "Y", "Z", "V"'

Like this

'variables = \"X\", \"Y\", \"Z\", \"V\"'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM