sczesla / PyAstronomy

A collection of astronomy-related routines in Python
152 stars 35 forks source link

Help with writing to text file -- novice question #31

Closed wglogowski closed 6 years ago

wglogowski commented 6 years ago

Hello I apologize for the is this is not the correct place to post this type of question. I'm a high school teacher and novice using PyAstronomy. I found this code on the repository and I want to save the output into a text file. I tried a simple save.File.write() and when that did not work I tried to look up how nexa = pyasl.NasaExoplanetArchive() is used but I have not had any success with that. Can someone point me in the right direction to learn how to save the outputs of a nexa = pyasl.NasaExoplanetArchive() call?

Thank you Walter

Here is the snippet I have been using.

from PyAstronomy import pyasl import datetime as dt

nexa = pyasl.NasaExoplanetArchive() exoplanetName=raw_input ('enter exoplanet name, example Kelt-7 b') dat = nexa.selectByPlanetName(exoplanetName)

saveFile = open('/Users/xyz/Desktop/Kelt-7b', 'w')

saveFile.write(dat) saveFile.close()

DanielAndreasen commented 6 years ago

You can check the type of your data by writing type(dat) which will give you the information that you are working with a dictionary. I don't know any built-in way to save a dictionary to a file, but you can use this small function.

def saveDict(d):
         with open('File.txt', 'a') as f:
             for key in d.keys():
                 s = '{}: {}\n'.format(key, d[key])
                 f.write(s)

Be careful, this will append (a) data to the same file. It can be beneficial to give a filename to the function as well. Use the function as saveDict(dat). Good luck

wglogowski commented 6 years ago

Thank you so much, that worked!

sczesla commented 6 years ago

Hi,

You could also have a look at the "pickle" module, which offers a built-in way to save and restore dictionaries (and many other Python objects).

Cheers, Stefan

from PyAstronomy import pyasl
import datetime as dt
import pickle

nexa = pyasl.NasaExoplanetArchive()
dat = nexa.selectByPlanetName("Kelt-7 b")

pickle.dump(dat, open("tmp.pickel", 'wb'))

datload = pickle.load(open("tmp.pickel", 'rb'))

print(datload)