astropy.io.ascii.write string to file without quotes

353 views Asked by At

I am trying to write a string and a float into a file using:

t=['SDSS J2000']
data=[10] 
astropy.io.ascii.write([t,data] ,'data.dat',names=['name','num'],formats={'name':'%s','num':'%f'})

the output file is:

name num
"SDSS J2000" 10.000000

how can I write the string to file without the quotes, like this:

SDSS J2000 10.000000
2

There are 2 answers

0
Jean-François Fabre On BEST ANSWER

You provided 2 data and 2 values, so astropy quotes the data to be able to read it back.

Do you really need astropy for this? Standard python does it easily using str.format:

t=['SDSS J2000']
data=[10]
with open("data.txt","w") as f:
    f.write("{} {} {:f}".format(*(t[0].split()+data)))

if you really want to achieve that using astropy you can use quotechar set to space (and use the option to avoid displaying header):

astropy.io.ascii.write([t,data] ,'data.dat',names=['name','num'],format='no_header',quotechar=' ',formats={'name':'%s','num':'%f'})

this writes:

  SDSS  J2000  10.000000

so too many spaces, expected when you try to twist the library's arm into writing data that cannot be read back reliably

EDIT: another way to do it is to let astropy write its quotes and remove them afterwards, using io.StringIO to avoid writing/reading/writing to disk:

import astropy.io.ascii
import io

t=['SDSS J2000']
data=[10]
buf=io.StringIO()
astropy.io.ascii.write([t,data] ,buf,names=['name','num'],format='no_header',formats={'name':'%s','num':'%f'})
with open("data.dat") as f:
    f.write(buf.getvalue().replace('"',""))

file now contains:

SDSS J2000 10.000000
1
Essex On

You could split with space as delimiter and you split one more time with " as delimiter.

For example (I don't try it) :

first = str.split(string, delimiter=' ')

if you display the result : print first[0] gives "SDSS

Then :

second_1 = str.split(first[0], delimiter = '"')
second_2 = str.split(first[1], delimiter = '"')

you will obtain SDSS with second_1[1]

Then you return :

print second_1[1] + second_2[0] + first[2]

will give : SDSS J2000 10.0000

enter image description here

As I said, It's an example, I didn't try it ! But the logic is there. I think it exists a really better answer than mine, but it's a way to do that