Files
So your wondering each time I run my program it doesn't remember anything... can I make a program remember the previous time it ran?
Lets start off with reading from a file... (I am going to explain don't worry)
my_file = "example.txt"
with open(my_file, "r") as f:
# File is now open for read-only!
print(f.read())
# This is very handy/nice
Assuming the data in the file is just a single number... (Being the times we ran our program)
2
Ok so there we now have our file read.
Let's break it down...
We use with open instead of just open so we don't need to play with 'oops we left the file open' errors.
with open("example.txt", "r") as f:
# File is open
# File is closed, f also does not exist!
What is f?
f is a file handle... this allows us to say read the entire file or readline for just reading 1 line at a time ...
We can also do this
my_file = []
with open("example.txt", "r") as f:
for l in f:
# itterate over each line in the file!
my_file.append(l) # Adds a new Element to the list
for l in my_file:
print(l) # this is the same as if you did print(f.read()) except we are out of the file now
This example shows that we read the file then with the file closed we still have the file contents!
Now let's get into writing to a file...
There are 2 ways to write to a file with different meaning!
Let's go over the little "r" in our open statement
- "r" means read, this is read-only we can't do any writes.
- "w" means write, danger this rewrites the entire file!
- "a" means append, this adds to the last line of the file.
- "b" means binary mode, this allows you to read/write/append to a file that is say an image or music or video
Yes some of these you can merge together... "rw" for a read and write file access!
Or the more common "rb" for read binary... or "wb" write binary.
So let's get our program so it will be complete:
# times, how many times did we run this program
times = 0
with open("example.txt", "r") as f:
l = f.read()
l = l.strip()
times = int(l)
# All this converts the line into a integer so we can do math to it!
times += 1 # Add one to the variable, but keep the contents the same. Not an assign!
print("I have ran {0} times!".format(times))
with open("example.txt", "w") as f:
f.write("{0}".format(times))
# Save the number of times and then exit the program!
3
And so on each time we run our program.
Up next JSON