0

I'm doing a python "project" for my class! Like I want to make the computer choose random students who to sit with and where! Well... I know how to do it my self, but i want to make it automated with JSON. Uhm.. like when i run the command and then the computer randomly chooses two students and I want to store that choice with JSON, so when i run the command again to check for the other students it wont try to choose the ones that have been already chosen before and that are stored in JSON file.

import random

#whotositwith
names1 = ('')
names2 = ('')
whotositwith = (random.choice(names1) + " - " + random.choice(names2))
bankcouple = whotositwith

#wheretosit
banka = '1'
nxenesit_numer = ('')
wheretosit = ("Nxënësit numër " + random.choice(nxenesit_numer) + " në bankën e " + banka)
banka = wheretosit
print(bankcouple)

Don't mind the language, it is not fully in English! :)

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
PanicKk
  • 13
  • 7
  • 1
    You can `open` a file and use `json.dump(obj, fp)` to store your obj's json representation to that file – dcg Mar 27 '19 at 21:56
  • Can you show me an example using the code above?^^ – PanicKk Mar 27 '19 at 21:57
  • Ummm... this is taking long xD. Do you have a discord? If you do add me Pan!cKk#6666 and lets talk there! – PanicKk Mar 27 '19 at 22:08
  • Possible duplicate of [How do I write JSON data to a file?](https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file) – Pedro Rodrigues Mar 28 '19 at 01:28

1 Answers1

0

You can do something like this

import json
myObj = {'prop1': 130, 'prop2': "bob"}
with open('myfile.txt', 'w') as fp:
    json.dump(myObj, fp)

EDIT: That will save myObj to myfile.txt in json format.

UPDATE: If you want to read the json you can do it as follows:

with open('myfile.txt') as fp:
    myObj = json.load(fp)
dcg
  • 4,187
  • 1
  • 18
  • 32
  • Thanks! What i wanna do now is that when i run the random.choice command to make the code skip what it has chosed if it is already stored in... example: myfile.txt – PanicKk Mar 27 '19 at 22:04
  • @PanicKk I've updated my answer to read a `json` file into an `object` – dcg Mar 27 '19 at 22:08
  • I got it! Now it reads and gets stored in the file but when i re run it, it just updates it, it doesn't add a new line with the new choice! How to make it store it all not update that one!? – PanicKk Mar 27 '19 at 22:21
  • @PanicKk when you load the json modify it (e.g., add the choice) and then write the modified object back to disk. – dcg Mar 27 '19 at 23:07