Lecture 14
Lecture 14
File Processing
Files are an element of storage on your systems that are managed by
the operating system.
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
Number of students = 50
Sum = 3068
Average = 61
Writing into Files
Writing into files in python can be performed as shown below;
>>> f.read()
'Hey, welcome to my python class!'