Skip to content
Save in Python
Profile icon
hacker
has Hacker Plan
InvisibleOne

If you want to save something in python, there are two ways you can go about it. One, is with pickle. I won't be covering that since it is a bit more complicated then the technique I use.
Ok, the first thing that you need to do is create a python file. Then a .txt file.
I named mine ‘save.txt’
In the python file, define the variables that you would like to save:

name = ‘forthethethethe’ fav_code = ‘python’ age = 12345 moo = ‘cow’

Alrighty, now we need to save these to the file. Define a function called ‘save()’

def save(): #open the file o = open(‘save.txt’, ‘w’) o.write(name + ‘ ‘ + fav_code + ‘ ‘ + str(age) + ‘ ‘ + moo) #make sure to close the file o.close()

Ok, so now we have our information in a file, how do we get it out? First, define a function called ‘load()’

def load(): #First we need to open up the file r= open(‘save.txt’, ‘r’) #now, we need to define a list that will hold the data save_list = r.read().split() #this should split the data into a list #now we’ll set the variables equal to the data we extracted from the file name = save_list[0] fav_code = save_list[1] age = int(save_list[2]) moo = save_list[3] #close the file r.close()

Now, we need to test if this works. First, we’ll set the variables to an input:

name = input(‘Name: ‘) fav_code = input(‘Favorite coding Language: ‘) age = input(‘How old are you? ’) moo = input(‘What animal moo’s? ‘)

We’ll input Bob for name, then Python, 45, and pig.
Then we’ll save the data:

save()

Then load it:

load()

Next we’ll check if it actually saved the data, we’ll print it out:

print(“Your name is: “ + name) print(“Your favorite coding language is: “ + fav_code) print(“Your age is: “ + str(age)) print(“A “ + moo + ‘ says moo’)

Result:

Your name is: Bob Your favorite coding language is: Python Your age is: 45 A pig says moo

So there you have it, a way to save a list of variables into a text file.
I hope you learned something, and if you didn’t, throw some rotten fruit then I hope you enjoyed reading this.
And if you want to see the repl, you can check it out here: https://repl.it/@forthethethethe/Saving-to-TXT#main.py

You are viewing a single comment. View All
Profile icon
personnosrep

I tried this but it said "IndexError: list index out of range"

Profile icon
InvisibleOne

This is a really old way of doing things, back when I didn't really know much. Now I suggest you use JSON

@personnosrep