+ 2
With python : how to store data to a file ?
How would you store data, for eg a list of lists, a dictionary, to a file, and then retrieve it later on, to modify it ? Is it more common to convert the data to a string and then write it to a .txt file ? with the need to convert it back ... or is it better to use pickle ? thank you
6 Respostas
+ 15
Use loop to write the list to txt file. And use split() method to read the list in the file.
+ 4
@Cpasgrave By using json format it enables you to use the data in different languages or send them to a rest api or retrieve them from your for example django endpoint via requests. If you use your own data representation everyone has to read into your formating and programming in a team can get complicated . Also by using json instead of pickle you can keep using the data outside the python programming language ...
Hope that kinda made sense ? =)
+ 3
For simple lists and dictionaries the json format is good and supported by python to read and write from and to files. pickel is only good if you want to store python specific classes and there state , for example a whole neural network witch is trained.
python docs to json:
https://docs.python.org/3/library/json.html
+ 2
@Nithiwat
Thanks. I'm on it. But if you have a simple example of the syntax you would use ; )
I would be happy to read it
thanks a lot for the quick answer !
+ 2
@Chrizzhigh
thank you, I'll make it an occasion to learn about json. I was trying to avoid something like this, but I'm sure I will need it soon. Could you explain me what is (are) the advantage(s) of using json instead of Nithiwat simple method ?
+ 2
@Chrizzhigh
Wow !
thanks so much !
Very rich answer for me. You are actually answering to questions I was keeping for later on the side of my brains !
And it gave me enough motivation to learn json right today !
have a nice week-end !