0

I currently have the array below and I am trying to export it to a .txt file and then importing it back into python, how would i go about doing this.

data = [
    {"score": "10", "grade": "E", "music": "song5", "maxcombo": "1", "perfect": "20", "great": "1", "good": "20", "miss": "1"},
    {"score": "20", "grade": "D", "music": "song4", "maxcombo": "2", "perfect": "20", "great": "2", "good": "20", "miss": "2"},
    {"score": "30", "grade": "C", "music": "song3", "maxcombo": "3", "perfect": "20", "great": "3", "good": "20", "miss": "3"},
    {"score": "40", "grade": "B", "music": "song2", "maxcombo": "4", "perfect": "20", "great": "4", "good": "20", "miss": "4"},
    {"score": "50", "grade": "A", "music": "song1", "maxcombo": "5", "perfect": "20", "great": "5", "good": "20", "miss": "5"},
]
Daniel
  • 11
  • 3
  • 8
  • 6
    What you're trying to do is [data serialization](http://en.wikipedia.org/wiki/Serialization). There are many ways to do this, entirely dependent on the format you choose. Take a look at the [csv](https://docs.python.org/2/library/csv.html), [pickle](https://docs.python.org/2/library/pickle.html), or [json](https://docs.python.org/2/library/json.html) libraries, for example. – jayelm Jun 08 '15 at 15:15
  • Also look at [`numpy.savetxt()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html) (if you go that route, you'll want to learn about [`numpy.array`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html), too). – Rick Jun 08 '15 at 15:18
  • what research did you do? i did a [**simple search**](https://www.google.com/search?q=write+dictonary+to+.txt+file+python&oq=write+dictonary+to+.txt+file+python&aqs=chrome..69i57.13236j0j7&sourceid=chrome&es_sm=91&ie=UTF-8) and came up with this result [**1st result**](http://stackoverflow.com/questions/20169493/how-write-a-dictionary-into-a-file) – John Ruddell Jun 08 '15 at 15:27

4 Answers4

3

There are many ways to save data, and the "right" one really depends on the context, use cases etc. However, your data format (a list of dicts) and your mention of a text file strongly suggests using a csv format. Python makes it easy with the standardlib's csv module.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • I love your answer because its not just giving someone an answer but giving them the opportunity to do it themselves! especially since there are many avenues to take to do this.. and there is already a bit out there to show them how to. – John Ruddell Jun 08 '15 at 15:29
  • @JohnRuddell If it's not a giveaway answer, they'll downvote you for a link answer. People are too attached to the Stack Overflow procedure to act for themselves. – Malik Brahimi Jun 08 '15 at 17:24
  • @MalikBrahimi this is not a link answer. the OP did not specify which method he wanted to use and obviously didn't do any research on this as a simple google search would provide him the solution.. which is why I like this answer and it has gotten upvotes. If someone has an actual issue and shows attempts then yes a code solution is the way to go. if there is no attempts and just a "I need you to do this for me" then they should work for an answer. Bruno's answer gives the necessary information for the OP to do it himself. He wont learn unless he does it himself. No handouts! :) – John Ruddell Jun 08 '15 at 17:31
0

This will write your data to an output file and help you get started. Then all you have to do is read it, which is rather easy.

import json

data = [
{"score": "10", "grade": "E", "music": "song5", "maxcombo": "1", "perfect": "20", "great": "1", "good": "20", "miss": "1"},
{"score": "20", "grade": "D", "music": "song4", "maxcombo": "2", "perfect": "20", "great": "2", "good": "20", "miss": "2"},
{"score": "30", "grade": "C", "music": "song3", "maxcombo": "3", "perfect": "20", "great": "3", "good": "20", "miss": "3"},
{"score": "40", "grade": "B", "music": "song2", "maxcombo": "4", "perfect": "20", "great": "4", "good": "20", "miss": "4"},
{"score": "50", "grade": "A", "music": "song1", "maxcombo": "5", "perfect": 
"20", "great": "5", "good": "20", "miss": "5"},
]

outputfile = 'output.json'# create this file
with open(outputfile, 'wb') as outfile:
    json.dump(row, outfile)
Mmm Donuts
  • 9,551
  • 6
  • 27
  • 49
0

It looks like you need a simple case of saving on to a text file. json is probably easy to start off with.

Try this: 1. Save the contents as json onto a text file 2. You may load the data back again and convert into json, which will work like dict objects.

file_path = '/tmp/dict_test.txt'
import json
data = [
    {"score": "10", "grade": "E", "music": "song5", "maxcombo": "1", "perfect": "20", "great": "1", "good": "20", "miss": "1"},
    {"score": "20", "grade": "D", "music": "song4", "maxcombo": "2", "perfect": "20", "great": "2", "good": "20", "miss": "2"},
    {"score": "30", "grade": "C", "music": "song3", "maxcombo": "3", "perfect": "20", "great": "3", "good": "20", "miss": "3"},
    {"score": "40", "grade": "B", "music": "song2", "maxcombo": "4", "perfect": "20", "great": "4", "good": "20", "miss": "4"},
    {"score": "50", "grade": "A", "music": "song1", "maxcombo": "5", "perfect": "20", "great": "5", "good": "20", "miss": "5"},
]

# dump the dict contents using json 
with open(file_path, 'w') as outfile:
    json.dump(data, outfile, indent=4, separators=(',', ':'))

# Let's read the data back again from the file
file_text = ''
with open(file_path, 'rt') as file_placeholder:
    lines = file_placeholder.readlines()
    file_text = ''.join(lines)  # This provides the whole file data as string

print('file_text = {}'.format(file_text))
# Load as json
json_text = json.loads(file_text)
print('json = {}'.format(json_text))
print('file_text type = {}; json_text type = {}'.format(type(file_text), type(json_text)))

You will get the following results:

file_text = [
    {
        "good":"20",
        "grade":"E",
        "great":"1",
.............
    }
]
json = [{'good': '20', 'grade': 'E', 'great': '1', 'music': 'song5', 'score': '10', 'miss': '1', 'maxcombo': ................ 'perfect': '20'}]
file_text type = <class 'str'>; json_text type = <class 'list'>
  • how would I then sort the data using something like this data = (sorted(data, key=operator.itemgetter("score"), reverse=True)) – Daniel Jun 08 '15 at 23:36
-1

You could pickle the data in a file, which will serialize the data list as a Python object:

pickle.dump(data, open('data.pkl', 'w')) # dump the contents of data into a file
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • 2
    i didn't downvote.. but it was probably because your answer had nothing to do with inserting into a .txt file (which was the OP's requirement) before your latest edit – John Ruddell Jun 08 '15 at 15:28
  • @JohnRuddell NoSQL databases are no different from JSON. You can store data. – Malik Brahimi Jun 08 '15 at 17:23
  • I know :) but what I was saying was the requirement was to write to a `.txt` file not store in a database.. which is probably where the downvotes came from :/ – John Ruddell Jun 08 '15 at 17:27