Text Files

One way to do this is with text files. Python supports opening text files without the need for importing any modules. To do this, just do:

myfile = open("mytext.txt","w")

In this, you’ll notice that the first parameter for the open function is the file we would like to open. The second parameter is how we would like to open it. These are common ways to open the file. We can use these as the second parameter:

myfile = open("mytext.txt","w")
myfile = open("mytext.txt","r")
myfile = open("mytext.txt","a")

To write to the file, make sure that you open the file in either “w” or “a” mode. Then, it’s as simple as doing: myfile.write(#info) where you can put the information that you would like to write as the parameter. If you need to write more than one time, you can just use another myfile.write(#info). Keep in mind, however, that the write method doesn’t put any spaces between your inputs, meaning that, for the below code, your text file would look like this: hello worldhi again

myfile = open("mytext.txt", "w")
myfile.write('hello world')
myfile.write('hi again')
myfile.close()

In addition to this, the write method only supports strings, meaning that you will either have to convert your data to a string using str(#data) or use formatting, like ‘%i’ % #number.

To read a file, you can do myfile.read(). This will return the text file’s data. If you would like to use the data, you could do

myfile = open("mytext.txt", "r")
mydata = myfile.read()