Filing


Mr Chigger     Excuse me, I saw your advertisement for flying lessons and I’d like to make an application.
Secretary     Appointment?
Mr Chigger     Yes, yes.
Secretary     Certainly. Would you come this way, please.
She gets up, clutching a file and trips off in a typical efficient secretary’s walk. Mr Chigger follows. Cut to a river. She goes straight in without looking to right or left, as if she does this routine as a matter of course. Mr Chigger follows. Halfway across the river they pass a couple of business executives hurrying in the opposite direction.

We come now to a crossroads.   We can’t keep typing all the questions in each time.  That would be too tedious!  So, we’re going to look at one way of “persisting” data.  That is, storing data from one session so that you can use it in another session.   We’re not going to cover the way of storing Python objects (since we haven’t really looked at objects yet), rather, we’re going to do some filing – with files on the filesystem.  This makes use of the open() function.

>>> import os.path
>>> nameOfFile ='python4kidsTest.txt'
>>> # just a test filename
... # check to see if the file is there
...
>>> os.path.exists(nameOfFile)
False
>>> # it's not there, so we can do this:
... fileObject = open(nameOfFile,'w')
>>> # fileObject is a file object
... # the open() function creates a file
... # with a name nameOfFile (not "nameOfFile")
... # (don't go further until you understand the previous line)
... # and then
... # it opens the file for writing - 'w'
... # if the file already exists it just opens it
... #
... os.path.exists(nameOfFile)
True
>>> # see, now it exists
>>> # let's write something to it:
... testMessage='This is a test message'
>>>
>>> fileObject.write(testMessage)

Finally, we should close the file:

>>> # after we've finished with a file we should close() it
... fileObject.close()

If you have access to the file system somehow, you can verify for yourself that the file is there. To find out what directory you are in type:

os.path.abspath('.')

And it will tell you (‘.’ is shorthand for the current directory).  From there you can look for a file called “python4kidsTest.txt” and open it to see that it really does include the test message we wrote (try “cat python4kidsTest.txt” from a command line on Linux, or use explorer if you are on some other operating system).  You can do it from Python by using os.listdir(‘.’) – try it.

If you aren’t brave enough to do that, you can try it yourself from Python by opening the file and reading from it:

>>> fileObject = open(nameOfFile,'r')
>>> # now we open the file for reading - 'r'
...
>>> fileContents = fileObject.read()
>>> # this reads the contents of the file
... # and stores it in fileContents
...
>>> fileContents
'This is a test message'
>>> fileObject.close()

Now, let’s do it again, this time with feeling:

>>> fileObject = open(nameOfFile,'w')
>>> # note 'w' for Writing (ie sending data *to* the file)
... # this overwrites the file!
...
>>> fileObject.write('A new message\n')
>>>
>>> fileObject.close()
>>>
>>> fileObject= open(nameOfFile,'r')
>>> print fileObject.read()
A new message
>>> # you don't need to store it in a variable first
... fileObject.close()
>>>

Can you see that when we opened the file for writing again, it wrote over the original message we had in there?  If you’d rather append or add to what is there, you can use the ‘a’ file mode:

>>> # to add stuff to the file we use 'a':
... fileObject= open(nameOfFile,'a')
>>>
>>> for i in range(10):
...     newMessage='Writing another line, number '+str(i)+'\n'
...     fileObject.write(newMessage)
...
>>> fileObject.close()
>>>
>>> fileObject = open(nameOfFile,'r')
>>> # note 'r' for Reading (ie getting data *from* the file)
... print fileObject.read()
A new message
Writing another line, number 0
Writing another line, number 1
Writing another line, number 2
Writing another line, number 3
Writing another line, number 4
Writing another line, number 5
Writing another line, number 6
Writing another line, number 7
Writing another line, number 8
Writing another line, number 9
>>> fileObject.close()

See that the previous data we’d written to the file (‘a new message\n’) was still there when we read it?

Exercise:

Choose a file name, assign it to a variable called nameOfFile.  Use os.path.exists to see if it exists.  If so, choose another name, otherwise, use open to open the file and write a message of your choosing to it, then close the file, open it for reading, read the contents back then close the file.

Note

Often programmers use a shorthand for both the file object and the file name.  It is not unusual, for example to see something like:

FN=’somefile.txt’

f=open(FN,’w’)

f.close()

End Note:

Ooops! Did you see I slipped up? I said we weren’t worrying about objects, and then the very next thing I told you that fileObject was, well, a file object.  Maybe I have to bite the bullet and next give you a gentle introduction to objects…

About these ads

5 Responses to Filing

  1. Pingback: Tweets that mention Filing « Python Tutorials for Kids 8+ -- Topsy.com

  2. Pingback: Links 4/10/2010: DebConf10 Report, ODF is Green | Techrights

  3. Pingback: Omigosh: Happy New Year « Python Tutorials for Kids 8+

  4. Pingback: Really GUI (more on Buttons, images and handlers) « Python Tutorials for Kids 8+

  5. Pingback: MineCraft config editor part 2 « Python Tutorials for Kids 8+

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 67 other followers

%d bloggers like this: