0

I have been wprking on this code today and the last process i have to do is to save the data i get to a .txt file, i am not sure how to do this and would greatly appreciate some help if at all possible, here is the code;

import random

char1=str(input('Please enter a name for character 1: '))
strh1=((random.randrange(1,12))//(random.randrange(1,4))+10)
skl1=((random.randrange(1,12))//(random.randrange(1,4))+10)
print('%s has a strength value of %s and a skill value of %s'%(char1,strh1,skl1))

char2=str(input('Please enter a name for character 2: '))
strh2=((random.randrange(1,12))//(random.randrange(1,4))+10)
skl2=((random.randrange(1,12))//(random.randrange(1,4))+10)
print('%s has a strength value of %s and a skill value of %s'%(char2,strh2,skl2))

I have researched the json function, but i am not sure how to use is because I want the data to be saved in a certain of 'char1(eg steve) has a stength of strh1(eg13) and a skill of skl1(eg21)' and then repeat this for the other character. If anyone could help me with this that would be really great, thanks !

Charlie1995
  • 29
  • 1
  • 7
  • While I'm sure an answer for the general case will come popping up shortly, if you are running on linux, you could pipe the output of this program from stdout to a text file and save it that way. `python program.py > my_save` – BlackVegetable Apr 02 '14 at 17:15

1 Answers1

3

Use python's file IO. Replace your print statement with:

line = '%s has a strength value of %s and a skill value of %s'%(char1,strh1,skl1)
with open('output', 'a') as opfile: # This creates the file if it does not exist and opens it in the append mode
    opfile.write(line)
opfile.close()

Do the same for the second character.

JSON is a format used to store data as attribute value pairs. If you wanted to store your data as:

{"data":[{"char":"steve", "strength":"13", "skill":"21"}, {...}]}

then, you would have to create a JSON object as above and then write the above JSON to a file with the json dump method as:

json.dump(json_object, opfile)

EDIT:

If you have a path to the file that you want to write to, you can specify the absolute path in the open call:

with open('/home/homedir/output.txt', 'a') as opfile:
shaktimaan
  • 11,962
  • 2
  • 29
  • 33
  • where could i retrieve the file from once the program is run ? – Charlie1995 Apr 02 '14 at 17:29
  • 1
    @user3370761 The file will be created in the current working directory. This answer - http://stackoverflow.com/questions/5137497/find-current-directory-and-files-directory explains what a current working directory is in Python – shaktimaan Apr 02 '14 at 17:33
  • and if i had a file I wanted to save it to where would i put the folder address – Charlie1995 Apr 02 '14 at 17:35