learning to program with python

23
Learning to Program With Python Beginners’ Class 7

Upload: thad

Post on 24-Feb-2016

46 views

Category:

Documents


0 download

DESCRIPTION

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.” - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Learning to Program With Python

Learning to ProgramWith Python

Beginners’ Class 7

Page 2: Learning to Program With Python

TopicsFiles!

Page 3: Learning to Program With Python

Limitations so farIn 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.

Page 4: Learning to Program With Python

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

Page 5: Learning to Program With Python

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

Page 6: Learning to Program With Python

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

Page 7: Learning to Program With Python

Files in pythonThe 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.

Page 8: Learning to Program With Python

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

Page 9: Learning to Program With Python

File modeshttp://

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

Page 10: Learning to Program With Python

File modes, word of warningStudy 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.

Page 11: Learning to Program With Python

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.

Page 12: Learning to Program With Python

File methods -- readingThere 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.

Page 13: Learning to Program With Python

The read() methodIf 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.

Page 14: Learning to Program With Python

The readline() methodThis 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.

Page 15: Learning to Program With Python

The readlines() methodReturns a list of strings representing each

line in the file, starting from the current position in the file.

Page 16: Learning to Program With Python

Using a file with a loopYou 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.

Page 17: Learning to Program With Python

The seek methodThis 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.

Page 18: Learning to Program With Python

The tell methodThis 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.

Page 19: Learning to Program With Python

The write methodThis 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

Page 20: Learning to Program With Python

The close methodJust 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!

Page 21: Learning to Program With Python

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.

Page 22: Learning to Program With Python

The with statementThe 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.

Page 23: Learning to Program With Python

ExamplesNow let’s try and add to our good ol’ ATM

example.