Reputation: 13
I'm trying to copy several lines of code from one python file to another.
The idea here is that I'm setting up a simple character creator for a text-based adventure game and I need to transfer the code over to a charcter sheet to use later on in the project.
I've tried using the .write function, but it doesn't accept integers
edit;Grammar
edit2;messed up in the 'else' bit
import sys
C_sheet=open("CharacterSheet.txt", 'w')
strength=10
dexterity=10
cunning=10
magic=10
mana=200
health_points=100
name=input("Name your character; ",)
C_sheet.write(name)
invalid2=True
def job():
role=input("Choose your role: Fighter(F), Mage(M), Thief(T): ", )
role=role.upper()
if role=="F":
st=(strength+5)
dex=(dexterity+0)
cun=(cunning-3)
mag=(magic-5)
mn=(mana-50)
hp=(health_points+25)
C_sheet.write("Fighter")
C_sheet.write(st)
C_sheet.write(dex)
C_sheet.write(cun)
C_sheet.write(mag)
C_sheet.write(mn)
C_sheet.write(hp)
C_sheet.close()
invalid2=False
else:
print("invalid")
invalid2=True
while invalid2:
job()
I'm trying to get the other file to look something like this
name=("placeholder")
st=15
dex=10
cun=7
mag=5
mn=150
hp=225
Upvotes: 1
Views: 74
Reputation: 13106
You are right, fh.write
only takes strings for files opened in w
or wt
mode. To get around this, you can use:
with open('somefile.txt', 'w') as fh:
fh.write('%d' % 5) # for ints
fh.write('%f' % 6) # for floats
fh.write('%s' % 'string') # for strings
# OR str.format syntax
with open('somefile.txt', 'w') as fh:
fh.write('{}'.format(5)) # transferrable to all types of variables
with open('somefile.txt', 'w') as fh:
fh.write(f'{5}') # will work for all variables
f-strings would be my vote, as it works the same for all variables, though string-formatting with {}
and %
is portable for python3 and python2, if that's an issue.
To get the format you are looking for with both options:
with open('somefile.txt', 'w') as fh:
fh.write('dex = %d' % dexterity)
# will write "dex = 10" or whatever you have substituted
with open('somefile.txt', 'w') as fh:
fh.write(f'dex = {dexterity})
Upvotes: 1