Reputation:
I am making a text based game that once finished should write certain variables to a text file:
==============
Story0:
-----------
Players name: name
Players characteristic: characteristic
This works fine, however what I wish to implement is a way for the function this
text comes from to also display which story it is generating meaning that it would write: StoryX
on the X
'th time that the program has been run.
I am unfamiliar with writing to and reading from python files and I'm afraid I am very far off what would be the best solution. The following code represents what I have so far (providing an error):
def Endscript(numberofcycles):
with open("playerstories.txt", 'a') as f:
f.write("================\n")
f.write("Story" + str(numberofcycles) + ": \n")
f.write("-----------\n")
f.write("Players name: " + Player.name)
f.write("\n")
f.write("Players characteristic: " + Player.char)
f.write("\n")
with open("number.txt", "r") as f:
numberofcycles = f.readline()
numberofcycles = int(numberofcycles)
numberofcycles += 1
with open("number.txt", "w") as f:
numberofcycles = str(numberofcycles)
f.write(numberofcycles)
What I have attempted to do here is to change the value of a number, (yes just one number) from within the number.txt
file in accordance with the changing X
value.
Thank you for any help you can provide
Upvotes: 0
Views: 169
Reputation: 157
Is this what you mean?
def Endscript():
with open("playerstories.txt", 'a') as f:
with open("number.txt", "r") as file:
numberofcycles = file.readline()
numberofcycles = int(numberofcycles)
f.write("================\n")
f.write("Story" + str(numberofcycles) + ": \n")
f.write("-----------\n")
f.write("Players name: " + Player.name)
f.write("\n")
f.write("Players characteristic: " + Player.char)
f.write("\n")
with open("number.txt", "w") as f:
numberofcycles += 1
numberofcycles = str(numberofcycles)
f.write(numberofcycles)
The error is caused by the undefined numberofcycles, if so it is because you haven't read into the txt file to retrieve the numberofcycles.
Upvotes: 2
Reputation: 559
You have the right idea, just remember that each run your game will be a completely independent process so your Endscript()
function really does not know the numberofcycles
unless you have already read that from disk. Here is quick function to access a single file and increment the value each time, returning that value for your use.
import os
def increment_counter(file_name):
if not os.path.exists(file_name):
with open(file_name, 'w') as fp:
fp.write("1")
return 1
else:
with open(file_name, 'r') as fp:
current_count = int(fp.read().strip())
with open(file_name, 'w') as fp:
fp.write(str(current_count + 1))
return current_count + 1
fname = 'test_counter.txt'
print(increment_counter(fname))
print(increment_counter(fname))
print(increment_counter(fname))
print(increment_counter(fname))
Output:
1
2
3
4
You can couple this with a reset_counter()
which just deletes the file to reset it
Upvotes: 0