0

I have written some code that creates two strength and skill values for two different characters, i would now like to be able to save the output to a text file called 'Characters', i have tried other methods but i don't know where it is saved to, ideally i would like the program to create the file so if the program was moved to a different computer it would create that file again to write to, this is the code so far;

import random

char1=str(input('Please enter a name for character 1: '))
strh1=((random.randrange(1,4))//(random.randrange(1,12))+10)
skl1=((random.randrange(1,4))//(random.randrange(1,12))+10)
line = '%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,4))//(random.randrange(1,12))+10)
skl2=((random.randrange(1,4))//(random.randrange(1,12))+10)
line = '%s has a strength value of %s and a skill value of %s'%(char1,strh1,skl1)

I would like it to save the data in two lines of the format in a txt file:

char1(e.g steve) has the strength value of strh1(e.g 12) and a skill value of skl1 (eg. 17) then repeat on the next line for char2

I have tried two differnt methods (json and open output, a) but its not working as i cant find the file it writes to, so if somone could help me with a solution that would be really good, thanks !

EDIT: i am writing in windows

Charlie1995
  • 29
  • 1
  • 7

2 Answers2

3
char_data1 = {
   "name":"steve",
   "level":1,
    "inventory":["cloak","dagger"],
    "whatever else":"something"
};

char_data2 = {
   "name":"cookie",
   "level":1,
    "inventory":["cigarettes","methamphetamine"],
    "whatever else":"something else"
};
char_data = [char_data1,char_data2]

import json
json.dump(char_data,open("character_data.dat","wb"))


char_data_loaded = json.load(open("character_data.dat"))

its pretty straight forward ... the file "character_data.dat" is created where ever your current working directory is

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1

If you need to know the default location where your files will be saved, you can use:

import os
print (os.getcwd())

... which shows:

M:\

... on my networked Windows PC if I run this code from IPython and:

C:\usr\sjl\python

... if I run it from a Windows command prompt in that directory.

See also Find current directory and file's directory.

Community
  • 1
  • 1
Simon
  • 10,679
  • 1
  • 30
  • 44