简体   繁体   中英

How to save my variables to a txt file from a program

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 !

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM