1 / 23

Learning to Program With Python

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.”

thad
Download Presentation

Learning to Program With Python

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Learning to ProgramWith Python Beginners’ Class 7

  2. Topics • Files!

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. 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.”

  9. 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.’

  10. 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.

  11. 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.

  12. 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.

  13. 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.

  14. 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.

  15. The readlines() method • Returns a list of strings representing each line in the file, starting from the current position in the file.

  16. 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.

  17. 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.

  18. 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.

  19. 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

  20. 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!

  21. 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.

  22. 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.

  23. Examples • Now let’s try and add to our good ol’ ATM example.

More Related