Chapter - 6tony Gaddis Python Book
Chapter - 6tony Gaddis Python Book
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.
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.
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
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.
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.
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.
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.
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
Reference_image
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.
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.
or
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
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