0% found this document useful (0 votes)
9 views10 pages

Chapter+6+Sections+1 3

Chapter 6.1-3 discusses file handling in programming, emphasizing the importance of saving data for future use through files. It covers the types of files (text and binary), methods of accessing data (sequential and random), and the steps for file operations (open, process, close). Additionally, it provides examples of writing to and reading from files, as well as using the 'with' statement for better file management.
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)
9 views10 pages

Chapter+6+Sections+1 3

Chapter 6.1-3 discusses file handling in programming, emphasizing the importance of saving data for future use through files. It covers the types of files (text and binary), methods of accessing data (sequential and random), and the steps for file operations (open, process, close). Additionally, it provides examples of writing to and reading from files, as well as using the 'with' statement for better file management.
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/ 10

Chapter 6.1-3: Working with files.

So far, we have been using print and input functions to display and enter data to a program. The print
provides connectivity between a program and the output device and with this connectivity, the output
data can be displayed on the output device (the default is the computer screen). The input function
provides connectivity between a program and the input device (the default input device is the keyboard.
In both cases the data must be a string. Although, the print function will convert all arguments to string
before displaying them, using the f-string as an argument, the conversion to string will be done by the f-
string expression when evaluated.

As has been described previously, the input function will always return a string to the program. If any
data other than string is expected, the string must be converted using the appropriate function. The
return data is typically assigned to a variable for use in the program.

The display output data and the input data from the keyboard are temporary. They cease to exist when
the program and the interpreter shell are closed. If you need to see the output data again, you have to
run the program and in running the program, the input data must be entered again from the keyboard.

Ideally, if you need the output data without running the program the output must be saved into
permanent storage. Similarly, if you need to re-enter the same input data again when you run a
program, having the input data in a permanent will save time.

To save time, data must be saved for future use. Files are used to store output data for future use and
input data when needed for future runs of the program. Data stored in a file is permanent. From the
process perspective of data, there are two types of files, namely input or output file (read or write file).
From the perspective of data type, we have text file or binary file.

A text file contains strings (typically ASCII characters), and a binary file contains binary data. The text file
contains human understandable characters while binary file contains only machine understandable
characters.

In this note, we will use text files. Binary files are used to store container objects that will be discussed in
subsequent chapters.

There are two ways to access data from a file:

1. Sequential access: data is accessed one at a time from top to bottom is an orderly fashion. The
data that appears first must be accessed before the data that appears after it.
2. Random access: data is accessed in a random fashion. There is no particular order for accessing
data in the file.

The files used in the notes have only sequential access.

When dealing with files, a program will write output data to file (as opposed to displaying to a display
screen using print function) and will read data from file (as opposed entering data from keyboard using
input function).
There are three steps involved with dealing the files a program:

1. Open the file: the first step is to open the file; this loads the file to the memory and makes it
available to your program. This process establishes the connectivity between the file and the
program.
2. Process the file: the step involving reading or writing data to the file.
3. Close the file: this last step is very important when done processing the file, the file must be
closed. Not closing the file after use may result in undesirable consequences such as data loss.

Opening a file.

The open function is used to open a file. The open function loads the file to memory and returns an
object called file object or pointer to the file. The file object is typically assigned to a variable.

The open function accepts two string objects. The first string object represents the file name (may
include directory path) and the second string object represents the open mode.

The open mode can be a write, read or append mode.

1. Write mode uses “w” to denote the string. Opening a file using the write mode will create the
file if the file does not exist or will erase the contents of an existing file in its entirety. Use this
mode with caution. You can only write the file.
2. Read mode uses “r” to denote the string. This mode opens the file to only read from it.
3. Append mode uses the “a” to denote the string. This mode can create the file if it does not exist
but cannot erase contents of existing file.

Syntax for opening a file.

file_object = open(filename, mode)

The file_object is a variable to hold the file object. The file_object is an iterable object and it is used it in
a for loop.

The filename is a string representing the file. The file must be in an accessible directory. You can use the
r-string (called raw string) if the directory path is included in the filename as in the example below.

fObj = open(r'c:\users\danir\desktop\text.txt', 'r')

The filename is “text.txt” and fObj is the file object and the open mode is read only (“r”). The r-string is
designated with the r prefix to specify the directory path of the file.
Processing a file depends on the open mode.

Use the write or writelines method to write string data to the file.

The write method accepts a single string argument and writes to the file object. The argument string is
written to a single or multiple lines, including the newline separator.

The writelines method accepts a list of string objects or a string argument that with no newline
separator and writes to the file object. When using writelines include in the newline separator.

Syntax

file_object.write(text)

file_object.writelines(list of strings)

Note that the scope operator (dot) is used to indicate that write and writelines are both methods of the
file object.

Example 1 Contents of data.txt


fObj = open(r'c:\users\danir\desktop\data.txt', 'w') Daniel
Professor
fObj.write('Daniel\n')
Math and Computer Science
fObj.writelines(['Professor\n', 'Math and Computer Science\n'])

fObj.close()

Example 2: Write a program that will prompt a user to enter the first and last names of 5 students and
their GPAs and write to file.

fObj = open(r'c:\users\danir\desktop\data.txt', 'w')

for _ in range(5): Contents of data.txt

first_name = input('Enter first name: ') Lyons Williams 3.56


Tasha Potter 3.8
last_name = input('Enter last name: ') Patience Walker 3.15
John Wheeler 2.89
gpa = float(input('Enter gpa: '))
Kyle Paterson 3.65
fObj.write(first_name + ' ' + last_name +

' ' + str(gpa) + '\n')

fObj.close()

In this example, the gpa is converted to string first before writing to file. Conceptually, a file consists of
records and each record consists of fields and each field which represents specific data. Typically, a
record represents a single line in a file as in the student gpa records in the above example, although it is
possible to have a record spans multiple lines.

Example 3: Write a program that will prompt the user to enter 5 stock items in the grocery store. Each
item (record) consists of product name, unit price and stock quantity.

fObj = open(r'c:\users\danir\desktop\data.txt', 'w')

for _ in range(5):
Contents of data.txt
prod_name = input('Enter product name: ')
Milk 3.99 25.0
unit_price = float(input('Enter the unit price: ')) Sugar 2.85 10.0
qty = float(input('Enter the stock quantity: ')) Chocolate 2.55 100.0
Bread 3.05 30.0
Green Tea 2.95 20.0
fObj.write(prod_name + ' ' + str(unit_price) +

' ' + str(qty) + '\n')

fObj.close()

There are four methods to read from a file.

1. Using the readline method to read one line or a single record at a time from the file. This
method has no argument, but it returns a string object like the input function. This method will
return an empty “” is there is not data to read from the file.
2. Using the readlines method to all the lines or records in the file. This method accepts no
argument and will return the list of strings representing the lines or records in the file.
3. Using the read method to read contents in the file as a single string. The string includes the new
separator.
4. Using the file object as an iterable object. As an iterable object, each line of the file can be
thought of as an item or a record in the sequence.

Displayed Output
Example 1: Write a program to read and display the data in
the data.txt in Example 3 using readline. Milk 3.99 25.0
fObj = open(r'c:\users\danir\desktop\data.txt', 'r')
Sugar 2.85 10.0
item = fObj.readline()
Chocolate 2.55 100.0
while item != "":

print(item) Bread 3.05 30.0

item = fObj.readline() Green Tea 2.95 20.0


fObj.close()
From the display, you would notice that a newline character is included to each line read from the file.
You can remove the newline character by stripping it off from the item using the strip method of a string
object.

The item.strip(arg) will return a string object representing the string item with arg removed.

Displayed Output
fObj = open(r'c:\users\danir\desktop\data.txt', 'r')
Milk 3.99 25.0
Sugar 2.85 10.0
Chocolate 2.55 100.0
item = fObj.readline()
Bread 3.05 30.0
while item != "": Green Tea 2.95 20.0

print(item.strip('\n')) #strip the newline character from item.

item = fObj.readline()

fObj.close()

Using the readlines method to accomplish the same result above.

fObj = open(r'c:\users\danir\desktop\data.txt', 'r')

all_records = fObj.readlines() #return a list of lines

for record in all_records:

print(record.strip('\n'))

fObj.close()

Using the read method to accomplish the same result above.

fObj = open(r'c:\users\danir\desktop\data.txt', 'r')

all_records = fObj.read() #string of all lines

for record in all_records.split('\n'):

print(record.strip('\n'))

fObj.close()

Here, we introduce the split method of a string object. The string.split(arg) will return a list of substrings
in the string object that are separated by the string argument.

string = “Fayetteville#State#University”

string.split(“#”)
will result in [“Fayetteville”, “State”, “University”]

Using the file object as an iterable sequence.

fObj = open(r'c:\users\danir\desktop\data.txt', 'r')

for record in fObj: #fObj is an iterable object

print(record.strip('\n'))

fObj.close()

Specifying the file keyword argument in a print will redirect the display from the print function to be
strong in the file object.

fObj = open(r'c:\users\danir\desktop\data.txt', 'w')

print(f'Test #1 {89}', file = fObj) Contents of data.txt

print(f'Test #2 {79}', file = fObj) Test #1 89


Test #2 79
print(f'Test #3 {90}', file = fObj) Test #3 90
Test #4 89
print(f'Test #4 {89}', file = fObj)

fObj.close()

Instead of displaying the string to the screen, string is stored in the file object using the file keyword
argument.

Using the with open statement can simplify the ways files are handled in Python and it no longer
necessary to close the file; the interpreter is able to automatically close the file.

The syntax is:

with open(filename, mode) as alias:

block_statement

Example #1

with open(r'c:\users\danir\desktop\data.txt', 'w') as fObj:

print(f'Test #1 {89}', file = fObj)

print(f'Test #2 {79}', file = fObj)


print(f'Test #3 {90}', file = fObj)

print(f'Test #4 {89}', file = fObj)

Example #2
Contents of data.txt
with open(r'c:\users\danir\desktop\data.txt', 'w') as
fObj: The square of 0 is 0
The square of 1 is 1
for num in range(5):
The square of 2 is 4
fObj.write(f'The square of {num} is {num*num}\n') The square of 3 is 9
The square of 4 is 16

It is possible to open multiple file objects in a single with open statement.

with open(file1, mode) as alias1, open(file2, mode) as alias2:

block_statement

Example 2: Write a program that will generate 20 random integers between 0 and 44

import random as rd

with open('w_data.txt', 'w') as wObj:

for _ in range(20):

#save a random number to file

wObj.write(str(rd.randrange(45))+'\n')

Example 4: Write a program that will read integers from w_data.txt and write each integer and the
reminder when divided by 2 to f_data.txt.

with open('w_data.txt', 'r') as fObj1,\

open('f_data.txt', 'w') as fObj2:

for value in fObj1: #read file

#remove newline character

value = value.strip('\n')

#write to write file

fObj2.write(f'{value}, {int(value)%2}\n')
As mentioned previously, a consists of records and a record consists of a field and a field is a single piece
of data. Files are used for maintaining database systems.

With the file processing discussed, it is possible to write a program that can query the database – add a
record, delete a record and search for a record. These are the three basic operations in a database
system.

Write an inventory database system for a small retail grocery store.

Each record has the product name, the unit price and the quantity in stock.

1. To add a record or increase the quantity, prompt the user to enter product name, unit price and
quantity in stock and write to file. Use the append mode to add to file only if the item is not
already in the file. Otherwise, add to the quantity in stock.
2. To delete a record. Prompt the user to enter the record to delete.
3. Search the file for a record. Prompt the user to enter the product name and return record.
4. Write a menu to simulate the inventory system.

#Inventory System
import os

#add a record
def addRecord():
p_name = input('Enter the product name: ')
u_price = float(input('Enter the unit price: '))
qty = float(input('Enter the stock quantity: '))

old_qty = get_qty(p_name)#

if old_qty != 0: #record already in file


qty += old_qty
delRecord(p_name) #record entire record

with open ('inventory.txt', 'a') as ifile:


ifile.write(f'{p_name} {u_price} {qty}\n')

#get quantity given the product name


#if product is not in the file, return 0
def get_qty(name):
qty_value = 0
with open ('inventory.txt', 'r') as ifile:
for line in ifile:
#record is a list of fields [name, u_price, quantity]
record = line.split() #uses the default space separator
if record[0] == name: #record found
qty_value = float(record[2])
break
return qty_value

#delete a record
def delRecord(name):
with open ('inventory.txt', 'r') as rfile,\
open('temp.txt', 'w') as ofile:
#copy records except the record with name to temp file
for line in rfile:
record = line.split()
if record[0] != name:
ofile.write(line)
#remove the original file
os.remove('inventory.txt')

#rename the new file as the original file


os.rename('temp.txt', 'inventory.txt')

#search for a record and return it


def search(name):
with open ('inventory.txt', 'r') as ifile:
for line in ifile:
record = line.split() #uses the default space separator
if record[0] == name:

return line #return the record if found

return '' #return an empty string if not found

#menu function
def inventory():
fObj = open("inventory.txt", "w")
fObj.close()
while True:
code = int(input('0 for quit\n1 for ' +\
'search\n2 for delete record\n' +\
'3 to add record' +\
'\nEnter code_______:'))
if code == 0:
print(f'Bye!')
break
elif code == 1:
product = input('Enter product name: ')
print(search(product))
elif code == 2:
product = input('Enter product name: ')
delRecord(product)
elif code == 3:
addRecord()
else:
print(f'Wrong Code!')

inventory()

You might also like