230 likes | 364 Views
Learning to Program With Python. Beginners’ Class 7. Topics. Files!. Limitations so far. In every example we’ve looked at so far, the program is always “running for the first time.”
E N D
Learning to ProgramWith Python Beginners’ Class 7
Topics • Files!
Limitations so far • In every example we’ve looked at so far, the program is always “running for the first time.” • All the variables are erased when the program terminates, and when you run it again, it will start from the top as if it were the first time you ever ran it.
RAM • Program data such as that is mostly held in your computer’s RAM, which is temporary memory that is constantly being reapportioned as different programs call for it. • RAM remembers nothing long-term.
Hard Drive • The files on your computer, however, are stored in the hard drive, which is a different sort of memory designed to work differently. • Even when the power is shut off, the hard drive remembers all the data that has been saved to it. • To understand the physical difference in memory, you’d have to study electronic engineering. We won’t be getting into that.
Files • This brings us to our main point– if you want your program to save information long-term, so that the second and third and fourth time the program runs, it remembers relevant data from previous executions, you have to save your data to files. • Python has a very convenient interface for doing this.
Files in python • The most basic thing to know is the built-in open() function. • The open() function generally takes 2 arguments, the name of the file and the mode in which to open it, e.g.: >>> open(“example.txt”, “r+”) #of course that ‘r+’ makes no sense yet.
File modes • Depending what “mode” a file is opened in, you can either read from it, write over it, append to it, erase it, or some combination of the above. • In file-mode speak, “r” stands for “read”, “w” stands for “write”, “a” stands for “append”, and “+” essentially means “read and write.”
File modes • http://stackoverflow.com/questions/1466000/python-open-built-in-function-difference-between-modes-a-a-w-w-and-r • The top answer to this question is extremely informative. Note that ‘truncate’ in this context means ‘erase entire content of file,’ and ‘stream’ means ‘the position in the file at which text will be added.’
File modes, word of warning • Study that link well! It is instinctive to think “I want to write to a file, I will use ‘w’”, but both “w” and “w+” erase the entire file contents when the file is opened. So “w” really means overwrite. • Probably you actually want either “r+” or “a+” if you are writing to a file, depending how you’re going to do it.
Using open() • A call to the open() function returns a special kind of object which we might essentially just call a file. • You almost always want to assign the result of open() to a variable. Otherwise you can’t use the result! >>> f = open(“example.txt”, “r+”) >>> type(f) <class '_io.TextIOWrapper'> #Fancy, but it’s just a file.
File methods -- reading • There are 3 convenient methods for reading from a file in python: • f.read() ---> Returns a single string containing the entire content of the file. • f.readline() ---> Returns a single string containing the next line of the file. • f.readlines() ---> Returns a list of all the lines in the file.
The read() method • If you open any mode that allows reading, you can use the .read() method to take in the entire contents of the file as a string. • .read(size) takes an optional argument that allows you specify the number of characters to read in. If you specify more than there are in the file, it will simply take the whole file.
The readline() method • This will read from the current position in the file up to the next newline, returning a single line of the file. The “current position” is then moved to the beginning of the next line.
The readlines() method • Returns a list of strings representing each line in the file, starting from the current position in the file.
Using a file with a loop • You can also read a file like this: f = open(“example.txt”, “r+”) for line in f: doSomethingWith(line) • Iterating over a file this way gives you each successive line.
The seek method • This lets you change the current position in the file, allowing you to adjust where you’re reading from and writing to. This may or may not be useful depending how you’re doing things. • f.seek(22, 0) would move the current position to 22 characters past the start of the file. It is probably unwise to attempt to seek past the length of the file, which could result in unexpected behavior.
The tell method • This simply tells you your current position in the file. >>> f.tell() 6 >>> • So we’re at position 6: there are 6 characters prior to this position in the file.
The write method • This is the standard way to write text to a file. You simply give it a string, and it writes to the current position in the file, assuming the file was opened in a write-compatible mode, which is basically anything except “r”, which is read-only. • It returns the number of characters written, as an int. >>> f.write(“hallo how are you”) 17
The close method • Just as you have opened a file, it is appropriate that you should close it when you’ve finished. It’s good practice, and in large programs can make a difference in contexts where many things are happening. Leaving a file open when you’re done with it is never a good idea. >>> f.close() #It’s that simple!
The close method • Note that the variable f still exists after “closing”….it simply can’t be used for reading or writing anymore. You would have to use the open() function again in order to resume activity.
The with statement • The best way to work with files, and to guarantee that they are closed when you are done with them, is to use the with statement. with open(“example.txt”, “r+”) as f: #Do something with f in an indented block. #f is exactly the same file object as before. #The difference is that after you un-indent, #f gets closed automatically.
Examples • Now let’s try and add to our good ol’ ATM example.