0% found this document useful (0 votes)
276 views7 pages

Chapter - 6tony Gaddis Python Book

The document discusses file input/output in Python. It covers: 1) Opening, reading from, and writing to files using methods like open(), read(), write(), close(). 2) Different file types (text, binary), access methods (sequential, direct), and naming conventions. 3) Using loops like for to process files line-by-line. 4) Organizing file data into records with fields and processing records using iteration. 5) Handling exceptions using try/except to gracefully handle errors like dividing by zero.

Uploaded by

Arslan Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
276 views7 pages

Chapter - 6tony Gaddis Python Book

The document discusses file input/output in Python. It covers: 1) Opening, reading from, and writing to files using methods like open(), read(), write(), close(). 2) Different file types (text, binary), access methods (sequential, direct), and naming conventions. 3) Using loops like for to process files line-by-line. 4) Organizing file data into records with fields and processing records using iteration. 5) Handling exceptions using try/except to gracefully handle errors like dividing by zero.

Uploaded by

Arslan Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Chapter 6: Files & Exceptions

6.1 Introduction to File Input and Output


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 store reports, image editors store image, games save
data and web browser cookies all are examples of it. In case of an office all payment and payroll data
is kept in a file.

Programmers usually refer to the process of saving data in a file as “writing data” to the file. When a
piece of data is written to a file, it is copied from a variable in RAM to the file. The term output file is
used to describe a file that data is written to. The process of retrieving data from a file is known as
“reading data” from the file. The term input file is used to describe a file from which data is read. It
is called an input file because the program gets input from the file.

There are three steps involve when a file is used by a program I) open the file (reading from or
writing on it), II) process the file (data is written or read) and III) close the file.

Types of Files: Text file & binary file


A text file contains data that has been encoded as text, using a scheme such as ASCII or Unicode
where A binary file contains data that has not been converted to text.

File Access Methods


Sequential access (like a cassette) and Direct access (like mp3)

Filenames and File Objects


Here we mean mp3, txt or doc with file name represented in windows. Each operating system has its
own rules for naming files. Many systems support the use of filename extensions, which are short
sequences of characters that appear at the end of a filename preceded by a period (which is known
as a “dot”).

In order for a program to work with a file on the computer’s disk, the program must create a file
object in memory. A file object is an object that is associated with a specific file and provides a way
for the program to work with that file. In the program, a variable references the file object. This
variable is used to carry out any operations that are performed on the file.

Opening a File
Use open function to open a file.

file_variable = open (filename, mode)

The file_variable is the name of the variable that will reference the file object, filename is a string
specifying the name of the file and mode is a string specifying the mode (reading, writing, etc.) in
which the file will be

alpha_name = open('sales.txt', 'r')

It will open file name sales.txt for variable alpha_name for reading “r” purpose only.
Specifying the Location of a File
When you pass a file name that does not contain a path as an argument to the open function, the
Python interpreter assumes the file’s location is the same as that of the program.

You can also specify a path as well as a filename in the argument that you pass to the open
function.

test_file = open(r'C:\Users\Blake\temp\test.txt', 'w')

The r prefix specifies that the string is a raw string. This causes the Python interpreter to read the
backslash characters as literal backslashes. Without the r prefix, the interpreter would assume that
the backslash characters were part of escape sequences, and an error would occur.

Writing a Data to a File


A method is a function that belongs to an object and performs some operation using that object.
Once you have opened a file, you use the file object’s methods to perform operations on the file.

file_variable.write(string)

It will allow you to write but make sure you open file with “w” or “a” mode, otherwise error will
occur.

alpha_file.write(“alpha male”)

Once a program is finished working with a file, it should close the file. Closing a file disconnects the
program from the file. In some systems, failure to close an output file can cause a loss of data. This
happens because the data that is written to a file is first written to a buffer, which is a small “holding
section” in memory. Following statement closes the file that is associated with customer_file:

customer_file.close()

Reference_image

Here we created a file opo.txt and written in it hello and how are you string. Notice each of the
strings written to the file end with \n, which you will recall is the newline escape sequence.

Reading Data from a file


If a file has been opened for reading (using the 'r' mode) you can use the file object’s read method to
read its entire contents into memory. When you call the read method, it returns the file’s contents
as a string.

Reference_image

There is a little mistake Arslan alpha.close line but you can correct it in later work!
Many programs need to read content one at a time in that case we will use readline method to read
a line from a file. Where (A line is simply a string of characters that are terminated with a \n.)

Reference_image

The gap or blank line you see after hello, how are you or other two lines is due to (\n) in code.

Concatenating a Newline to a String


it is usually necessary to concatenate a \n escape sequence to the data before writing it, it ensures
that data is in separate line.

You can also write file name with name_var.write(f'{name_1}\n') code instrad of
name_var.write(name_1+'\n') code.

Reference_image

Reading a String and Stripping the Newline from It


Sometime complications occur because when the strings are printed, the \n causes an extra blank
line to appear. If you want to remove the \n from a string after it is read from a file, you can do it
with method named rstrip that removes, or “strips,” specific characters from the end of a string.

>> name = 'Joanne Manchester\n'

>> name = name.rstrip('\n')

Reference_image

Appending Data to an Existing File


Appending data to a file means writing new data to the end of the data that already exists in the file.

In Python, you can use the 'a' mode to open an output file in append mode, which means the
following.

• If the file already exists, it will not be erased. If the file does not exist, it will be

created.

• When data is written to the file, it will be written at the end of the file’s current

contents.

When you will use and write new lines it will be added at the end of previous code.

Writing and Reading Numeric Data


To assign numbers first we assign a numeric int or float then we convert it into string to show in txt
file.

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

file_variable.write(str(variable_number)+”\n”)

So, numbers are saved as strings with this code in file and when you open file to read they are
always read as strings.
Reference_image

Reading the int or float from the file, involves file format. Here you have to put int for main format
and then readline the inside data.

1. infile = open('numbers.txt', 'r')


2. string_input = infile.readline()
3. value = int(string_input)
4. infile.close()

or

1. infile = open('numbers.txt', 'r')


2. value = int(infile.readline()) #readline method is used as the argument to the int function
3. infile.close()

6.2 Using Loops to Process Files


When we are typically involved with large files loop is typically involves. Check the code how loops
are involved.

Reference_image

Reading a File with a Loop and Detecting the End of the File
Suppose you need to write a program that reads all of the amounts in the sales.txt file and calculates
their total. You can use a loop to read the items in the file, but you need a way of knowing when the
end of the file has been reached.

Reference_image

Most programming languages provide a similar technique for detecting the end of a file.

Reference_image

Using Python’s for Loop to Read Lines


When you simply want to read the lines in a file, one after the other, this technique is simpler and
more elegant than writing a while loop that explicitly tests for an end of the file condition. Here is
the general format of the loop:

for variable in file_object:

statement statement etc.

In the general format, variable is the name of a variable, and file_object is a variable that references
a file object. The loop will iterate once for each line in the file. The first time the loop iterates,
variable will reference the first line in the file (as a string), the second time the loop iterates, variable
will reference the second line, and so forth.

Reference_image
6.3 Processing Records
The data that is stored in a file is frequently organized in records. A record is a complete set of data
about an item, and a field is an individual piece of data within a record. Record is like name, Ids and
department of an officer where all these things its fields.

You can use iteration and count function for name, ids and department. Remember concept of
iteration here Arslan and reading, writing method. Also make sure that you remember spaces code
like \n and print “” because while reading file they can be mess because you can forget removing \
n with rstrip.

Reference_image_6.15_spotlight

Reference_image_6.16_spotlight

Reference_image_6.17_Spotlight

6.4 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 e.g. trying to divide a
number by 0. The long error you will code is called traceback, it gives information in the line that
caused the exception. You can prevent exceptions using right logic and if, else statement. But there
are some errors that cannot be avoided like input value for int or float being typed in str, when
you asked the person write forty instead of 40, it will give rise to ValueError, an error type in
python, you can handle such errors and codes with code called exception handler written with
try/except statements.

Try:
statement
statement etc.
except ExceptionName:
statement
statement etc.
Reference_image

Handling Multiple Exceptions


You can use different exceptions clause like for possible classified errors and for the a general
purpose you can use except: which had nothing in it.
Referebce_image

Using One except Clause to Catch All Exceptions


You can accomplish that in a try/except statement by writing one except clause that does not specify
a particular type of exception.

Displaying an Exception’s Default Error Message


When an exception is thrown, an object known as an exception object is created in memory. The
exception object usually contains a default error message pertaining to the exception. (In fact, it is
the same error message that you see displayed at the end of a traceback when an exception goes
unhandled.) When you write an except clause, you can optionally assign the exception object to a
variable, as shown here:
except ValueError as variable_name:
Reference_image

The else Clause


The try/except statement may have an optional else clause, which appears after all the except
clauses. Here is the general format of a try/except statement with an else clause:
try:
statement
statement etc.
except ExceptionName:
statement
statement etc.
else:
statement
statement etc.
The block of statements that appears after the else clause is known as the else suite. The statements
in the else suite are executed after the statements in the try suite, only if no exceptions were raised.
If an exception is raised, the else suite is skipped.

The finally Clause


The try/except statement may have an optional finally clause, which must appear after all the except
clauses. Here is the general format of a try/except statement with a finally clause:
try:
statement
statement etc.
except ExceptionName:
statement
statement etc.
finally:
statement
statement etc.
The block of statements that appears after the finally clause is known as the finally suite. The
statements in the finally suite are always executed after the try suite has executed, and after any
exception handlers have executed. The statements in the finally suite execute whether an exception
occurs or not. The purpose of the finally suite is to perform cleanup operations, such as closing files
or other resources. Any code that is written in the finally suite will always execute, even if the try
suite raises an exception.

What If an Exception Is Not Handled?


You can predict and use the right code to handle the exception but in case you are not aware of it
the best thing you can do is learn and analyse what is the best possible solution.

You might also like