PowerPoint Presentation
Basics in programming
Classes 7.
Reading from and Writing to a File
A file is a grouping of related data that can be read by a computer program.
Files maybe stored in many different places including the hard drive, a thumb drive, on a CD, at a network location, really any place where a program could have access to it.
Files
Files occur in many forms and sizes, a text file is a bunch of text written using an editor and usually stored on a hard drive.
Files can be read and written from Python programs.
Filesare another type of sequence as far as Python programs are concerned and we can iterate over them just as we would any sequence.
Files
Files are sequences of strings, one string for each line of the file.
To read from a file we open it and then iterate over the lines of the file.
Files
Files
The first line of the example opens the file for reading.
To write a file it may be opened for writing by using a “w” instead of a “r”.
You can also open a file with “a” for append to add to the end of an existing file.
Files
Files
When writing to a file you use the file.write method. Unlike the print function, you cannot write multiple items by separating them with commas.
The write method takes onlyone argument, the string to write. To write multiple items to a line of a file, you must usestring concatenation (i.e. the + operator) to concatenate the items together as was done
Files
It is frequently the case that a file contains more than one line that relate to each otherin some way.
For example, consider an address book program. Each entry in your addressbook may contain last name, first name, street, city, zip code, home phone number, and mobilenumber.
Typically, each of these pieces of information would be stored on a separate line in a file.
Files
program that reads such a file would need to read all these lines together and a for loop will not suffice. In this case it can be done if we use a while loop.
Files
Files
A while loop is used to read records from a file that are composed of multiple lines.
A for loop will not suffice because a for loop only reads one line per iteration.
Since multiple lines must be read, a while loop gives you the extra control you need.
Files
Files
Files
/docProps/thumbnail.jpeg