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

Lecture 14

The document provides an overview of file processing in Python, detailing how to open, read, write, and append to files using the built-in open() function. It explains the syntax for opening files, the different modes available (reading, writing, appending), and includes examples of reading file contents and writing data to files. Additionally, it demonstrates how to compute the average of scores read from a file and showcases the appending of new content to existing files.

Uploaded by

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

Lecture 14

The document provides an overview of file processing in Python, detailing how to open, read, write, and append to files using the built-in open() function. It explains the syntax for opening files, the different modes available (reading, writing, appending), and includes examples of reading file contents and writing data to files. Additionally, it demonstrates how to compute the average of scores read from a file and showcases the appending of new content to existing files.

Uploaded by

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

A d va n c e d P y t h o n

File Processing
Files are an element of storage on your systems that are managed by
the operating system.

Files are used to store information of varying types; images, text,


binary, video, database, program codes etc…

Python provides a built-in object that provides a managed way to


access file resources in your programs and on local or remote computer
systems
The built-in open() function is used to create a python file object
which serves as a link to a file residing on your computer.
Once the open() function has been used, you can then transfer strings
of data to and from the associated file using methods provided by the
file objects.
Opening Files
Before working with any file, it must first be opened. The syntax for
opening python files is as follows;
file_handle = open(file_path, file_mode)
file_path: is the path string showing where the file is stored on the local
system e.g ‘C:\python27\codes’
file_mode: is the mode in which the file is to be used. It typically takes
any of the following modes;

Mode Meaning
R Opening a file for reading
W Opening a file for writing, overwrites whatever is the file
A Opening a file for appending data to the end of a file, preserving the
existing content.
Opening Files
Now lets try open some a file named ‘poem.txt’ located in
‘C:\python27\codes\’
1 >>> f = open('c:\python27\codes\poem.txt','r')
2 >>> f
3 <open file 'c:\python27\codes\poem.txt', mode 'r' at
0x022B27B0>

Line 1 opens the specified file object for reading and store a
reference to the file in f
Line 3 shows us information about the opened file such as its full
path, file mode and memory reference.
Reading Files
Lets try to read some files;
1 >>> for line in f.readlines():
2 print line
3
OUR AFRICA
Our Africa, virtuous and seated with pride,
Distinct on her gun-throne of glory;
Taking her place amongst her equals;
A vibrant queen – unique in her very own way.
>>> open(r'c:\python27\codes\file2.txt','r').read()
'Federal University of Technology, \nPMB
704\nAkure,\nNigeria.'
>>> ff =
open(r'c:\python27\codes\file2.txt','r').read()
>>> print ff
Federal University of Technology,
PMB 704
Akure,
Nigeria.
Reading Files…
It is also possible to read from a file in byte by byte…
1 >>> ff =
2 open(r'c:\python27\codes\file2.txt','r')
3 # read the first 8 bytes i.e. characters
>>> print ff.read(8)
Federal
# read the next 20 bytes i.e. characters
>>> print ff.read(20)
University of Techn
>>> ff = open(r'c:\python27\codes\poem.txt','r')
>>> print ff.readline()
OUR AFRICA
Reading Files…
It is also possible to read from a file its content at once as a
1 >>> ff = open(r'c:\python27\codes\file2.txt','r')
2 >>> list_of_lines = ff.readlines()
3 >>> list_of_lines

[‘Federal University of Technology, \n', 'PMB


704\n', 'Akure,\n', 'Nigeria.']

>>> for line in list_of_lines:


print line

Federal University of Technology,


PMB 704
Akure,
Nigeria.
Example: read a list of scores from a file and then print out the sum and
average of the scores. The file contains 50 scores, each on a separate line.
1 # open the file for reading referenced as ‘ff’
2 >>> ff = open(r'c:\python27\codes\scores.txt','r')
3 # initialised an empty list/array
4 >>> scores = []
5 # iterate through each line, convert to string, remove any
‘\n’ char, then append to the list.
6 >>> for line in ff.readlines():
7 score = int(str(line).lstrip('\n'))
8 scores.append(score)
9 # compute average
10 >>> ave = float(sum(scores))/len(scores)

12 >>> print "Number of students = %d \n Sum = %d \n


Average = %d" % (len(scores), sum(scores),ave)

Number of students = 50
Sum = 3068
Average = 61
Writing into Files
Writing into files in python can be performed as shown below;

1 # open the file for writing


2 >>> f = open('c:\python27\codes\greetings.txt','w')
3
# print a line of greeting into the file
>>> f.write("Hey, welcome to my python class!")

# now lets read and display the content of the file


>>> f = open('c:\python27\codes\greetings.txt','r')

>>> f.read()
'Hey, welcome to my python class!'

- We used ‘w’ for writing.


- Writing with ‘w’ overwrites whatever is in the file before.
Appending to Files
1 # open the file for appending and then write to the file..
2 >>> f = open('c:\python27\codes\greetings.txt','a')
3 >>> f.write(“\nPlease download the compiler from \n \t
'wwww.python.org'! ")
# check the file if it was properly written..
>>> f = open('c:\python27\codes\greetings.txt','r')
>>> print f.read()
Hey, welcome to my python class!
Please download the compiler from
'wwww.python.org'!
# append another line, open for reading and print contents
>>> f = open('c:\python27\codes\greetings.txt','a')
>>> f.write("\nNow lets start coding!")
>>> f = open('c:\python27\codes\greetings.txt','r')
>>> print f.read()
Hey, welcome to my python class!
Please download the compiler from
'wwww.python.org'!
Now lets start coding!

You might also like