[Tutor] reading files

Alan Gauld alan.gauld at btinternet.com
Fri Sep 22 12:16:07 CEST 2006


>i cant understand the open command i tried the help command but still
> dont get i am trying to write twi programs one to keep track of 
> money
> phone numbers... and another to randomly print a statmint from a 
> file

The built in open command opens a file. That is it creates
a file object that you can manipulate in code.
It takes a filename (or full path) as a first argument.
It also takes a "mode2 as a second argument.
You can open a file in various modes but the most
common are read-only (argument is "r") and
write-only(argument is "w")

When you open the file it gives you a file object.
The file object has various methods that you can call.
So if you open a file for reading you can call the read()
method to get the file contents returned as a string.
If you opened it for writing you can call write() to write
your data to the file.

Opening a file to read requires that the file already exists,
and does not change the file on the disk in any way.

Opening a file to write will either create a new file
on the disk or overwrite an existing file, destroying
its existing contents. It is the programmers responsibility
to manage the consequences by creating a backup file
or whatever.

If you did not understand that, reply to the list with
the specific bits you didn't understand highlighted.

You might also like to try reading my Handling Files
topic in my tutorial which goes into more depth with
examples.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list