0% found this document useful (0 votes)
16 views

CP104 - Chapter 6 - Files and Exceptions

This document discusses files and exceptions in Python. It explains that files are used to save data for later use and describes common file types like text and binary. It also outlines the basic steps to open, process, and close a file. The document then demonstrates how to write data to and read data from files in Python using file objects and provides an example of handling exceptions with try/except statements.

Uploaded by

juliamicic10
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

CP104 - Chapter 6 - Files and Exceptions

This document discusses files and exceptions in Python. It explains that files are used to save data for later use and describes common file types like text and binary. It also outlines the basic steps to open, process, and close a file. The document then demonstrates how to write data to and read data from files in Python using file objects and provides an example of handling exceptions with try/except statements.

Uploaded by

juliamicic10
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

CP104 - Files and Exceptions - Chapter 6

When a program needs to save data for later use, it writes the data in a file.

The data can be read from the file at a later time.

● Word processors. Word processing programs are used to write letters, memos, reports,
and other documents. The documents are then saved in files so they can be edited and
printed.
● Image editors. Image editing programs are used to draw graphics and edit images,
such as the ones that you take with a digital camera. The images that you create or edit
with an image editor are saved in files.
● Spreadsheets. Spreadsheet programs are used to work with numerical data. Numbers
and mathematical formulas can be inserted into the rows and columns of the spread-
sheet. The spreadsheet can then be saved in a file for use later.
● Games. Many computer games keep data stored in files. For example, some games
keep a list of player names with their scores stored in a file. These games typically
display the players’ names in order of their scores, from highest to lowest. Some games
also allow you to save your current game status in a file so you can quit the game and
then resume playing it later without having to start from the beginning.
● Web browers. Sometimes when you visit a Web page, the browser stores a small file
known as a cookie on your computer. Cookies typically contain information about the
browsing session, such as the contents of a shopping cart.

This chapter discusses how to write data to files and read data from files. There are always
three steps that must be taken when a file is used by a program.

1. Open the file. Opening a file creates a connection between the file and the program.
Opening an output file usually creates the file on the disk and allows the program to write data
to it. Opening an input file allows the program to read data from the file.

2. Process the file. In this step, data is either written to the file (if it is an output file) or read
from the file (if it is an input file).

3. Close the file. When the program is finished using the file, the file must be closed. Closing a
file disconnects the file from the program.

Types of Files

In general, there are two types of files: text and binary. A text file contains data that has been
encoded as text, using a scheme such as ASCII or Unicode. Even if the file contains numbers,
those numbers are stored in the file as a series of characters. As a result, the file may be
opened and viewed in a text editor such as Notepad. A binary file contains data that has not
been converted to text. The data that is stored in a binary file is intended only for a program to
read. As a consequence, you cannot view the contents of a binary file with a text editor.
File Access Methods

Most programming languages provide two different ways to access data stored in a file:
sequential access and direct access. When you work with a sequential access file, you access
data from the beginning of the file to the end of the file. If you want to read a piece of data that is
stored at the very end of the file, you have to read all of the data that comes before it—you
cannot jump directly to the desired data. This is similar to the way older cassette tape players
work. If you want to listen to the last song on a cassette tape, you have to either fast-forward
over all of the songs that come before it or listen to them. There is no way to jump directly to a
specific song.

When you work with a direct access file (which is also known as a random access file), you can
jump directly to any piece of data in the file without reading the data that comes before it. This is
similar to the way a CD player or an MP3 player works. You can jump directly to any song that
you want to listen to.

Filenames and File Objects

Most computer users are accustomed to the fact that files are identified by a filename. For
example, when you create a document with a word processor and save the document in a file,
you have to specify a filename. When you use a utility such as Windows Explorer to examine
the contents of your disk, you see a list of filenames. Figure 6-3 shows how three files named
cat.jpg, notes.txt, and resume.docx might be graphically represented in Windows.

Opening a File

You use the open function in Python to open a file. The open function creates a file object and
associates it with a file on the disk. Here is the general format of how the open func- tion is
used:

file_variable = open(filename, mode) In the general format:

● file_variable is the name of the variable that will reference the file object.

● filename is a string specifying the name of the file.

● mode is a string specifying the mode (reading, writing, etc.) in which the file will be
opened.

Table 6-1 shows three of the strings that you can use to specify a mode. (There are other, more
complex modes. The modes shown in Table 6-1 are the ones we will use in this book.)
For example, suppose the file customers.txt contains customer data, and we want to open it for
reading. Here is an example of how we would call the open function:

customer_file = open('customers.txt', 'r')

Suppose we want to create a file named sales.txt and write data to it.

Here is an example of how we would call the open function: sales_file = open('sales.txt', 'w')

CLOSE

In Python, you use the file object’s close method to close a file. For example, the following
statement closes the file that is associated with customer_file:

customer_file.close()

WRITE FILE

# This program writes three lines of data to a file.


def main():

# Open a file named philosophers.txt.


outfile = open('philosophers.txt', 'w')

# Write the names of three philosphers to the file.


outfile.write('John Locke\n')
outfile.write('David Hume\n')
outfile.write('Edmund Burke\n')

# Close the file.


outfile.close()

# Call the main function.


if __name__ == '__main__':
main()

READ File

#This program reads and displays the contents # of the philosophers.txt file.

def main():

# Open a file named philosophers.txt.

infile = open('philosophers.txt', 'r')

# Read the file's contents.

file_contents = infile.read()

#Close the file.

infile.close()

#Print the data that was read into memory.

print(file_contents)

# Call the main function.

if __name__ == '__main__':

main()

Program Output

John Locke

David Hume

Edmund Burke

Exceptions

An exception is an error that occurs while a program is running, causing the program to
abruptly halt. You can use the try/except statement to gracefully handle exceptions.

This program divides a number by another number.


def main():

# Get two numbers.

num1 = int(input('Enter a number: '))

num2 = int(input('Enter another number: '))

# If num2 is not 0, divide num1 by num2 and display the result.

if num2 != 0:

result = num1 / num2

print(f'{num1} divided by {num2} is {result}')

else

print('Cannot divide by zero.')

# Call the main function. if __name__ == '__main__':

main()

You might also like