Reputation: 122
I am making a discord game bot, but I can't figure out how to save user data. This is extremely frustrating because I can't make edits, because then I gotta exit the Python Shell and everyone loses all their data.
Is there a way to have Python store the data even after I stop running the file?
I am using discord.py
, async
, and on_message
, but you can give me ctx.
EDIT: I am trying to save player data, which should usually be strings and variables
Upvotes: 1
Views: 4809
Reputation: 2299
Is there a way to have Python store the data even after I stop running the file?
Traditionally, if a program needs to store data longer than it is running, it writes to the disk and reads when it picks back up.
The pythonic way to do file I/O is:
with open("/path/to/file","mode-goes-here") as file_variable_name:
do stuff
Where "mode goes here" is one of the file modes. Make sure you Read up on them before setting it, or you'll lose your data.
This code creates an object named "file_variable_name" that you can read or write to. The object is only "alive" inside the indentation for the "with" statement. Once you go past the "with" statement, python will automatically close the file for you. Because it does a lot of the bookkeeping for you, that's why this is the recommended way of opening a file.
Writing to the object is as simple as:
file_object.write("strings here")
Reading from a file object is typically done by iterating through it:
for line in file_variable_name_goes_here:
do stuff
Where "line" here returns a string of every line in the file. Python decides what a line is based on your platform's line separator.
From there, you're ready to read and write to your disk. The most common format is CSV, which stands for "comma-separated values." If the wikipedia article is unclear, just open up Excel or something, make a spreadsheet with something in it, and you can save as a CSV. Any text editor is able to open a CSV. Open up the CSV you saved, and you'll have an idea of what it looks like.
What you want to do here is to have some function in your bot that will take the data you've stored and write it to a file. You will also want some other function that can take the data you've stored to a file and put it in memory.
Upvotes: 2