Ask coding questions

← Back to all posts
How to store and call something from a file?
TerrorbuildLuna (38)

I'm making a chatbot that stores user inputs as outputs for future use. I made a file and I've tried several things to try to get the chatbot to be able to recall all the vocabulary it has learned before when the programs starts. However, it just doesn't seem to work, no matter how I try. I searched online and there are no solutions. Please help me. (Btw, I'll mention you when I post the chatbot if you helped me)

CodeLongAndPros (1596)

I like what @SpicedSpices says, but he forgot a couple of very important things.

Always use a context manager:

with open(foo, bar) as f:

The open functions takes two args: filename and mode.

Filename, is, well, a filename.

Mode is one of these:
(r)ead, (w)rite, (a)ppend, (r)ead (b)ytes, (w)rite (b)ytes, (r)ead(+)write.

And, if you don't use with, you always have to call file.close()

CodeLongAndPros (1596)

@TerrorbuildLuna Sure.

Did it help? Mark it as the answer

CodeLongAndPros (1596)

@TerrorbuildLuna You’re not saving the input, is that normal?

SpicedSpices (297)

To read a text file or write to a text file, you will need to use the open() function. The open function takes a file and a mode, and will do something with that mode.

text = open('words.txt', 'r')

This will read whatever is in words.txt.

The mode can be many things. w will write to the file, r will read to the file, r+ can read and write to the file.

There are other functions that open() has such as read(), write(), append(), and close(), which will do their corresponding definitions. read() will read the file. write() will write to the file. append() will append strings to a new line on the file. close() will close the file.

Your error is that you only have a memory file. You need memory.txt for a text file. You also have .join() which needs to be .write(). The last thing is that you only have a r as the mode. It needs to be r+ to read and write.

TerrorbuildLuna (38)

@SpicedSpices Oh, it didn't seem to work... could you elaborate on your advice please?