(Pick The Date) : PPG Institute of Technology
(Pick The Date) : PPG Institute of Technology
5.1 FILES
A file represents a sequence of bytes on the disk where a group of related data is
stored.
File is created for permanent storage of data.
r
1 Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
rb
2 Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
r+
3 Opens a file for both reading and writing. The file pointer placed at the beginning
of the file.
rb+
4 Opens a file for both reading and writing in binary format. The file pointer placed
at the beginning of the file.
w
5 Opens a file for writing only. Overwrites the file if the file exists. Otherwise,
creates a new file for writing.
wb
6 Opens a file for writing only in binary format. Overwrites the file if the file exists.
Otherwise, creates a new file for writing.
w+
7 Opens a file for both writing and reading. Overwrites the existing file if the file
exists. Otherwise, creates a new file for reading and writing.
wb+
8 Opens a file for both writing and reading in binary format. Overwrites the existing
file if the file exists. Otherwise, creates a new file for reading and writing.
9 a
Opens a file for appending. The file pointer is at the end of the file if the file exists.
Otherwise, it creates a new file for writing.
ab
10 Opens a file for appending in binary format. The file pointer is at the end of the file
if the file exists. Otherwise, it creates a new file for writing.
a+
11 Opens a file for both appending and reading. The file pointer is at the end of the
file if the file exists. Otherwise, it creates a new file for reading and writing.
ab+
Opens a file for both appending and reading in binary format. The file pointer is at
12
the end of the file if the file exists. Otherwise, it creates a new file for reading and
writing.
file.closed
1
Returns true if file is closed, false otherwise.
file.mode
2
Returns access mode with which file was opened.
file.name
3
Returns name of the file.
5.2.3 Example
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
print ("Closed or not : ", fo.closed)
print ("Opening mode : ", fo.mode)
fo.close()
Output
Example
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
fo.close()
Output:
The write() method does not add a newline character ('\n') to the end of the string
Syntax
fileObject.write(string);
Example
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
fo.close()
Output:
foo.txt
5.4.1 read()
It reads specified the specified number of characters from the file.
If omitted it will read entire contents of the file.
Syntax:
f.read(size)
Here size is optional and returns a data of specified size
Program:
f=open(“new.txt”,’r’)
f.read(4)
Input file: (new.txt)
Python programming
Interpreted
Output:
‘Pyth’
5.4.2 readline()
It is used to read individual lines of a file.
It reads a file till the newline(\n) character is reached or end of file(EOF)
Syntax:
f.readline(size)
Here size is optional and returns a data of specified size
Program:
f=open(“new.txt”,’r’)
f.readline()
Input file: (new.txt)
Python programming
Interpreted
Output:
‘Python programming’
5.4.3 readlines()
It is used to read list of lines on the entire file.
Syntax:
f.readlines(size)
Here size is optional and returns a data of specified size
Program:
f=open(“new.txt”,’r’)
f.readlines()
Input file: (new.txt)
Python programming
Interpreted
Output:
[‘Python programming\n’, ‘Interpreted\n’]
f.open(“filename”,’a’)
Program:
f=open(“new.txt”,”a”)
f.write(“Easy to learn\n”)
f.close()
Input file: (new.txt)
Python programming
Interpreted
Output:
Python programming
Interpreted
Easy to learn
file.close()
1
Close the file. A closed file cannot be read or written any more.
file.flush()
2
Flush the internal buffer of file object.
file.fileno()
3 Returns the integer file descriptor to request I/O operations from the operating
system.
file.isatty()
4
Returns True if the file is connected to interactive, else False.
next(file)
5
Returns the next line from the file each time it is being called.
file.read([size])
6 It reads specified the specified number of characters from the file
If omitted it will read entire contents of the file.
file.readline([size])
7 It is used to read individual lines of a file.
It reads a file till the newline(\n) character is reached or end of file(EOF)
8 file.readlines([sizehint])
file.seek(offset[, whence])
9
Sets the file's current position
file.tell()
10
Returns the file's current position
file.truncate([size])
11 Truncates the file's size. If the optional size argument is present, the file is
truncated to (at most) that size.
file.write(str)
12
Writes a string to the file.
file.writelines(sequence)
13 Writes a sequence of strings to the file. The sequence can be any iterable object
producing strings, typically a list of strings.
5.8.1 flush()
The method flush() flushes the internal buffer of file objects.
Python automatically flushes the files when closing them.
Syntax
fileObject.flush()
Example
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
fo.flush()
fo.close()
Output
5.8.2 fileno()
The method fileno() returns the integer file descriptor which is used to request I/O
operations from the operating system.
PPG INSTITUTE OF TECHNOLOGY Page 10
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
Syntax
fileObject.fileno()
Example
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
print ("File Descriptor: ", fo.fileno())
fo.close()
Output
5.8.3 isatty()
The method isatty() returns True if the file is connected or associated with a terminal
device, else False.
Syntax
fileObject.isatty()
Example
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
ret = fo.isatty()
print ("Return value : ", ret)
fo.close()
Output
5.8.4 seek()
The method seek() sets the file's current position at the offset.
Syntax
fileObject.seek(offset, whence)
Parameters
offset − This is the position of the read/write pointer within the file.
whence − This is optional and defaults to 0 which means absolute file
positioning, other values are 1 which means seek relative to the current
position and 2 means seek relative to the file's end.
Example
Output:
5.8.5 tell()
The method tell() returns the current position of the file read/write pointer within the
file.
Syntax
fileObject.tell()
Example
Output
5.8.6 truncate()
The method truncate() truncates the file's size.
If the optional size argument is present, the file is truncated to (at most) that size.
Syntax
fileObject.truncate( size )
Example
Output
5.8.7 next()
Python 3 has a built-in function next() which retrieves the next item from the iterator
by calling its __next__() method.
If default is given, it is returned if the iterator is exhausted,
otherwise StopIteration is raised.
This method can be used to read the next input line, from the file object
Syntax
next(iterator,default)
Example
fo = open("foo.txt", "r")
print ("Name of the file: ", fo.name)
for index in range(5):
line = next(fo)
print ("Line No %d - %s" % (index, line))
fo.close()
Output:
5.8.8 write()
The write() method writes any string to an open file.
It is important to note that Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string
Syntax
fileObject.write(string);
Example
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
fo.close()
Output:
1 %c - character
2 %s - string conversion
6 %o - octal integer
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
Output
('-a', 'val')
('-b', 'val')
('-c', 'val')
5.11 MODULES
A module allows us to logically organize our Python code.
Grouping related code into a module makes the code easier to understand and use.
A module is a Python object with arbitrarily named attributes that we can bind and
reference.
Simply, a module is a file consisting of Python code.
A module can define functions, classes and variables.
A module can also include runnable code.
Example
5.11.1 The import Statement
We can use any Python source file as a module by executing an import statement in
some other Python source file.
The import has the following syntax:
When the interpreter encounters an import statement, it imports the module if the
module is present in the search path.
For example, to import the module support.py, we need to put the following
command at the top of the script −
import support
support.print_func("Zara")
Output:
Hello:Zara
A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening over and over again if multiple
imports occur.
5.11.2 The from...import Statement
Python's from statement lets us import specific attributes from a module into the
current namespace.
The from...import has the following syntax −
For example, to import the function fibonacci from the module fib, use the following
statement −
This statement does not import the entire module fib into the current namespace; it
just introduces the item fibonacci from the module fib into the global symbol table of
the importing module.
This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.
Output:
['__doc__','__file__','__name__','acos','asin','atan',
'atan2','ceil','cos','cosh','degrees','e','exp',
'fabs','floor','fmod','frexp','hypot','ldexp','log',
'log10','modf','pi','pow','radians','sin','sinh',
'sqrt','tan','tanh']
Here, the special string variable __name__ is the module's name, and __file__is the
filename from which the module was loaded.
If the module is not found, Python then searches each directory in the shell
variable PYTHONPATH.
If all else fails, Python checks the default path.
The module search path is stored in the system module sys as the sys.path variable.
The sys.path variable contains the current directory, PYTHONPATH, and the
installation-dependent default.
reload(module_name)
reload(hello)
Example:
#Mobile/MI.py
def MI():
print(“MI Phone”)
#Mobile/G4.py
def G4():
print(“G4 Phone”)
from MI import MI
from G4 import G4
import Mobile
Mobile.MI()
Mobile.G4()
Output
MI Phone
G4 Phone
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Example 1:
This example opens a file, writes content in the, file and comes out gracefully
because there is no problem at all −
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
Output:
Example 2:
This example tries to open a file where you do not have the write permission, so it
raises an exception −
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
Output:
try:
You do your operations here
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
try:
You do your operations here
......................
except(Exception1, Exception2,...ExceptionN):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
We can provide except clause(s), or a finally clause, but not both. We cannot
use else clause as well along with a finally clause.
PPG INSTITUTE OF TECHNOLOGY Page 25
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
Example
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can\'t find file or read data")
fh.close()
Output:
If you do not have permission to open the file in writing mode, then this will
produce the following result −
try:
You do your operations here
......................
except ExceptionType as Argument:
You can print value of Argument here...
This variable receives the value of the exception mostly containing the cause of the
exception.
The variable can receive a single value or multiple values in the form of a tuple.
This tuple usually contains the error string, the error number, and an error location.
Example
def temp_convert(var):
try:
return int(var)
Output
try:
if a<=0:
except ValueError as e:
print(e)
else:
Output:
PPG INSTITUTE OF TECHNOLOGY Page 27
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
Enter a number 0
Guess a number 10
Congratulations! You guessed it correctly
Output
Python is Simple
Python is interactive programming language
Python is Interpreted
Output:
Python is Simple
Python is interactive programming language
Python is Interpreted
Counter({'Python': 3, 'is': 3, 'Simple': 1, 'interactive': 1, 'programming': 1, 'language':
1, 'Interpreted': 1})
Case 1:
Contents of file(test.txt):
Hello world
Output(out.text):
Hello world