Unit 2 Functions, OOP, Exceptions, Files
Unit 2 Functions, OOP, Exceptions, Files
Python Functions
o Once defined, Python functions can be called multiple times and from any
location in a program.
o Our Python program can be broken up into numerous, easy-to-follow functions
if it is significant.
o The ability to return as many outputs as we want using a variety of arguments
is one of Python's most significant achievements.
o However, Python programs have always incurred overhead when calling
functions.
Syntax
Output:
Calling a Function
Calling a Function To define a function, use the def keyword to give it a name, specify
the arguments it must receive, and organize the code block.
When the fundamental framework for a function is finished, we can call it from
anywhere in the program. An illustration of how to use the a_function function can be
found below.
Output:
Output:
Function Arguments
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments
1) Default Arguments
Code
Output:
def fun(a,x=30,y,b=10):
print("a=",a,"b=",b)
fun(1,20)
Output:
ERROR!
def fun(a,x=30,y,b=10):
^
SyntaxError: non-default argument follows default argument
>
def fun(a,b=10,c=20):
print("a=",a,"b=",b,"c=",c)
fun(1,20)
def fun(a=1,b=1,c=1):
print("a=",a,"b=",b,"c=",c)
fun()
2) Keyword Arguments
Code
Output:
def fun(a=1,b=1,c=1):
print("a=",a,"b=",b,"c=",c)
fun(b=10,a=20)
def fun(a=10,b=1,c=1):
print("a=",a,"b=",b,"c=",c)
fun(c=30,b=20)
3) Required Arguments
Code
1.
2. # Defining a function
3. def function( n1, n2 ):
4. print("number 1 is: ", n1)
5. print("number 2 is: ", n2)
6.
7. # Calling function and passing two arguments out of order, we need num1 to be 20 a
nd num2 to be 30
8. print( "Passing out of order arguments" )
9. function( 30, 20 )
10.
11. # Calling function and passing only one argument
12. print( "Passing only one argument" )
13. try:
14. function( 30 )
15. except:
16. print( "Function needs two positional arguments" )
Output:
4) Variable-Length Arguments
If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.
This way the function will receive a dictionary of arguments, and
can access the items accordingly:
Code
def fun(**a):
print(a) #it will print Dictionary
fun(c=30,b=20)
Output:
{'c': 30, 'b': 20}
Example:
def fun(c,**a,d):
print(a)
print(c)
fun(10,a=10,d=30)
Error:
ERROR!
File "<string>", line 1
def fun(c,**a,d):
^
SyntaxError: arguments cannot follow var-keyword
argument
Example
def fun(c=10,**a):
print(a)
print(c)
fun(a=10,d=30)
Output:
{'a': 10, 'd': 30}
10
Example:
def fun(b,c=10,**a):
print(a)
print(c)
fun(40,30)
Output:
{}
30
Example
def fun(**a):
print(a)
# print(c)
fun(40,30)
ERROR!
Traceback (most recent call last):
File "<string>", line 5, in <module>
TypeError: fun() takes 0 positional arguments but 2
were given
Example:
def fun(**a):
print(a)
print(c)
fun(40)
Output:
ERROR!
Traceback (most recent call last):
File "<string>", line 5, in <module>
TypeError: fun() takes 0 positional arguments but 1
was given
Example:
def fun(c,**a):
print(a)
print(c)
fun(40)
Output:
{}
40
Example:
def fun(c,**a):
print(a)
print(c)
fun(40,a=10,b=20)
Output:
{'a': 10, 'b': 20}
40
Example:
def fun(**b,**a):
print(a)
print(c)
fun(b=50,a=500)
Example:
ERROR!
File "<string>", line 1
def fun(**b,**a):
^^
SyntaxError: arguments cannot follow var-keyword
argument
Example
def fun(**a):
print(a)
#print(c)
fun()
Output:
{}
Example
def fun(**a):
print(a)
#print(c)
list=[1,2,3]
fun(b=list)
Output:
{'b': [1, 2, 3]}
Example:
def fun(**a):
print(a)
#print(c)
list=[1,2,3]
fun(list)
ERROR
Example:
def fun(c,**a):
print(a)
print(c)
list=[1,2,3]
fun(list,b=[4,5,6],x=[10,20,30],y="amit")
Output:
{'b': [4, 5, 6], 'x': [10, 20, 30], 'y': 'amit'}
[1, 2, 3]
Example:
def fun(c,x,**a):
print(a)
list=[1,2,3]
fun(list,10,d=20,a=50,x=100)
Error:
Traceback (most recent call last):
File "/home/cg/root/657ed8daed710/main.py", line 5,
in <module>
fun(list,10,d=20,a=50,x=100)
TypeError: fun() got multiple values for argument 'x'
def fun(p,a,x):
print(a)
list=[1,2,3]
fun(20,a=50,p=100)
Example:
def fun(p,a,l):
print(a)
list=[1,2,3]
fun(20,a=50,90)
Output:
File "/home/cg/root/657ed8daed710/main.py", line 5
fun(20,a=50,90)
^
SyntaxError: positional argument follows keyword
argument
def fun(l):
return l*2
list=[1,2,3]
print(fun(list))
Output:
[1, 2, 3, 1, 2, 3]
def fun(**a):
return a
print(fun(a=10,b=20))
Output:
{'a': 10, 'b': 20}
Example:
def fun(**a):
a['a']=1000 #changing value in dictionary
return a
print(fun(a=10,b=20))
Output:
{'a': 1000, 'b': 20}
*args
def fun(*a):
print(*a)
print(a)
print(fun(10))
Output:
10
(10,)
None
Example:
def fun(*a):
print(*a)
print(a)
print(fun(10,20,30))
Output:
10 20 30
(10, 20, 30)
None
Example:
def fun(*a,c,d,b=1000):
print(*a)
print(f'a={a},b={b},c={c},d={d}')
print(a)
print(fun(10,d=110,c=20))
Output:
10
a=(10,),b=1000,c=20,d=110
(10,)
None
Example:
def fun(a=10,b=50,*c):
print(*c)
print(f'a={a},b={b},c={c}')
print(c)
print(fun(20,30))
Output:
a=20,b=30,c=()
()
None
Example:
def fun(a,b,**c,d):
print(c)
print(c)
print(fun(20,30,c=40,d=50))
Output:
File "/home/cg/root/657ed8daed710/main.py", line 1
def fun(a,b,**c,d):
^
SyntaxError: invalid syntax
Example:
def fun(*t):
print(t)
print(fun(111,222,[10,20,30],(40,50),{60,70},{"name":"
amit"}))
Output:
(111, 222, [10, 20, 30], (40, 50), {60, 70}, {'name':
'amit'})
None
When a defined function is called, a return statement is written to exit the function and
return the calculated value.
This way the function will receive a tuple of arguments, and can access
the items accordingly:
def my_function(*kids):
print("The youngest child is " + kids[2])
Related Pages
return Statement
When a defined function is called, a return statement is written to exit the function and
return the calculated value.
Syntax:
Code
Lambda functions can only refer to variables in their argument list and the global
domain name because they contain their distinct local domain.
Syntax
A lambda function can take any number of arguments, but can only have
one expression.
Syntax
lambda arguments : expression
x = lambda a : a + 10
print(x(5))
Example
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
Example
Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
EXAMPLE
x = lambda **a : print(a)
print(x(a=6,b=8))
Output:
{'a': 6, 'b': 8}
None
EXAMPLE
x = lambda b,c,*a : print(a,b,c)
print(x(1,2,3,4))
Output:
(3, 4) 1 2
None
Example:
x = lambda b,*a,c=10 : print(a,b,c)
print(x(1,2,3,4))
Output:
(2, 3, 4) 1 10
None
Example:
x = lambda b,*a,c : print(a,b,c)
print(x(1,2,3,4))
Output:
Traceback (most recent call last):
File "/home/cg/root/657ed8daed710/main.py", line 2, in <module>
print(x(1,2,3,4))
TypeError: <lambda>() missing 1 required keyword-only argument: 'c'
Say you have a function definition that takes one argument, and that
argument will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Example
def myfunc(n):
return lambda a : a * n
#it returns lambda function, not any value, returns lambda a:a*2 (i.e.
value of n)
mydoubler = myfunc(2)
# myfunc() returns lambda function that is saved in mydoubler, so my
doubler is now lambda function
Example
def myfunc(n):
return lambda a : a * n #returns lambda a: a*3
mytripler = myfunc(3) #mytripler is a lambda function
Or, use the same function definition to make both functions, in the same
program:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Code
Output:
Output:
Here, we can see that the initial value of num is 10. Even though the function number()
changed the value of num to 50, the value of num outside of the function remained
unchanged.
def fun(a):
a=0
print(id(a))
fun(a)
print(a)
print(id(a))
Output:
140200934097104
140200934097104
Code
Output:
Nested (or inner) functions are functions defined within other functions that
allow us to directly access the variables and names defined in the enclosing
function.
Defining an inner/nested Function
Simply use the def keyword to initialize another function within a function to
define a nested function.
Example
Output
Hello Amit
It is essential that the outer function be called so that the inner function can
execute.
Below will give not output as we have not called inner function
def innerFunc():
print(sample_text)
outerFunc('Hello Amit')
Example
Output
Example
Output
Hello Amit
Example
The following program changes the value of a variable inside the nested
function(inner function) −
Output
Welcome
Hello Amit
Here, the value of the outer function's variable remains unchanged. However,
the value of the outer function's variable can be modified. There are several
methods for changing the value of the outer function's variable.
Printing IDs
def outerFunc():
print(id(sample_str))
def innerFunc():
print(sample_str)
print(id(sample_str))
# calling an inner function inside the outer function
innerFunc()
print(sample_str)
print(id(sample_str))
outerFunc()
Output:
140591567492224
140591565048688
140591567492224
>
Output
['Welcome']
['Welcome']
Example:
Output:
['Hi PU', 'Hello students']
['Welcome to', 'Hello students']
['Hello Amit python']
There are cases when you wish to encapsulate a function or the data it has
access to in order to prevent it from being accessed from other parts of your
code.
When you nest a function like this, it becomes hidden to the global scope.
Because of this characteristic, data encapsulation is also known as data hiding
or data privacy.
Output
The inner function in the code above is only accessible from within the outer
function. If you attempt to call inner from outside the function, you will see
the error shown above.
Output
Syntax
The syntax of the Lambda Function is given below -
This function accepts any count of inputs but only evaluates and returns one
expression. That means it takes many inputs but returns only one output.
1. # Code to demonstrate how we can use a lambda function for adding 4 numbers
2. add = lambda num: num + 4 #add variable/object points to the Lambda Function
3. print( add(6) )
Output:
10
Here we explain the above code. The lambda function is "lambda num: num+4" in the
given programme. The parameter is num, and the computed and returned equation is
num * 4.
There is no label for this function. It generates a function object associated with the
"add" identifier. We can now refer to it as a standard function.
Output:
Now we compile the above code in Python, and after successful compilation, we run
it. Then the output is given below -
10
Program Code
Now we gave an example of a lambda function that multiply 2 numbers and return
one result. The code is shown below -
1. a = lambda x, y : (x * y)
2. print(a(4, 5))
Output:
20
Program Code
1. a = lambda x, y, z : (x + y + z)
2. print(a(4, 5, 5))
Output:
14
What's the Distinction Between Lambda and Def
Functions?
This program calculates the reciprocal of a given number:
Program Code:
1. # Python code to show the reciprocal of the given number to highlight the difference
between def() and lambda().
2. def reciprocal( num ):
3. return 1 / num
4.
5. lambda_reciprocal = lambda num: 1 / num
6.
7. # using the function defined by def keyword
8. print( "Def keyword: ", reciprocal(6) )
9.
10. # using the function defined by lambda keyword
11. print( "Lambda keyword: ", lambda_reciprocal(6) )
Output:
Explanation:
The function is called for every item of the list, and a new iterable or list is
returned that holds just those elements that returned True when supplied to the
function.
Here's a simple illustration of using the filter() method to return only odd numbers
from a list.
Program Code:
1. # This code used to filter the odd numbers from the given list
2. list_ = [35, 12, 69, 55, 75, 14, 73]
3. odd_list = list(filter( lambda num: (num % 2 != 0) , list_ ))
4. print('The list of odd number is:',odd_list)
Output:
The list of odd number is: [35, 69, 55, 75, 73]
Example
Calculate the length of each word in the tuple:
def myfunc(n):
return len(n)
Example:
def myfunc(a):
print(len(a))
return len(a) # returns len 5, then 6, then 6
Syntax
map(function, iterables)
Parameter Values
Parameter Description
More Examples
Example
Make new fruits by sending two iterable objects into the function:
Using Lambda Function with map()
A method and a list are passed to Python's map() function.
The function is executed for all of the elements within the list, and a new list is
produced with elements generated by the given function for every item.
The map() method is used to square all the entries in a list in this example.
Program Code:
Here we give an example of lambda function with map() in Python. Then code is given
below -
1. #Code to calculate the square of each number of a list using the map() function
2. numbers_list = [2, 4, 5, 1, 3, 7, 8, 9, 10]
3. squared_list = list(map( lambda num: num ** 2 , numbers_list ))
4. print( 'Square of each number in the given list:' ,squared_list )
Output:
Square of each number in the given list: [4, 16, 25, 1, 9, 49, 64, 81, 100]
List Comprehension
List comprehension offers a shorter syntax when you want to create a new
list based on the values of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with
the letter "a" in the name.
Without list comprehension you will have to write a for statement with a
conditional test inside:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line of code:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
print(newlist)
The Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
Condition
The condition is like a filter that only accepts the items that valuate to True.
Example
Only accept items that are not "apple":
The condition if x != "apple" will return True for all elements other than
"apple", making the new list contain all fruits except "apple".
Example
With no if statement:
Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
Example
You can use the range() function to create an iterable:
Example
Accept only numbers lower than 5:
Expression
The expression is the current item in the iteration, but it is also the outcome,
which you can manipulate before it ends up like a list item in the new list:
Example
Set the values in the new list to upper case:
Example
Set all values in the new list to 'hello':
Program Code:
Output:
A lambda function can take n number of arguments at a time. But it returns only
one argument at a time.
Python File Handling
Python File Handling
Introduction:
The file handling plays an important role when the data needs to be stored
permanently into the file. A file is a named location on disk to store related
information. We can access the stored information (non-volatile) even after the
program termination.
In Python, files are treated in two modes as text or binary. The file may be in the
text or binary format, and each line of a file is ended with the special character like
a comma (,) or a newline character. Python executes the code line by line. So, it
works in one line and then asks the interpreter to start the new line again. This is a
continuous process in Python.
o Open a file
o Read or write or append to a file
o Close the file
Opening a file
A file operation starts with the file opening. At first, open the File then Python will start
the operation. File opening is done with the open() function in Python. This function
will accepts two arguments, file name and access mode in which the file is accessed.
When we use the open() function, that time we must be specified the mode for
which the File is opening. The function returns a file object which can be used to
perform various operations like reading, writing, etc.
Syntax:
The files can be accessed using various modes like read, write, or append. The
following are the details about the access mode to open a file.
SN Access Description
mode
1 r (default) r means to read. So, it opens a file for read-only operation. The file
pointer exists at the beginning. The file is by default open in this mode
if no access mode is passed.
2 rb It opens the file to read-only in binary format. The file pointer exists
at the beginning of the file.
3 r+ It opens the file to read and write both. The file pointer exists at the
beginning of the file.
4 rb+ It opens the file to read and write both in binary format. The file
pointer exists at the beginning of the file.
5 w It opens the file to write only. It overwrites the file if previously exists
or creates a new one if no file exists with the same name. The file
pointer exists at the beginning of the file.
6 wb It opens the file to write only in binary format. It overwrites the file if
it exists previously or creates a new one if no file exists. The file pointer
exists at the beginning of the file.
7 w+ It opens the file to write and read both. It is different from r+ in the
sense that it overwrites the previous file if one exists whereas r+
doesn't overwrite the previously written file. It creates a new file
if no file exists. The file pointer exists at the beginning of the file.
8 wb+ It opens the file to write and read both in binary format. The file
pointer exists at the beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at the end
of the previously written file if exists any. It creates a new file if no file
exists with the same name.
10 ab It opens the file in the append mode in binary format. The pointer
exists at the end of the previously written file. It creates a new file in
binary format if no file exists with the same name.
11 a+ It opens a file to append and read both. The file pointer remains at
the end of the file if a file exists. It creates a new file if no file exists
with the same name.
12 ab+ It opens a file to append and read both in binary format. The file
pointer remains at the end of the file.
Let's look at the simple example to open a file named "file.txt" (stored in the same
directory) in read mode and printing its content on the console.
It is a read operation in Python. We open an existing file with the given code and then
read it. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run
it. Then the output is given below -
In the above code, we have passed filename as a first argument and opened file in
read mode as we mentioned r as the second argument. The fileptr holds the file
object and if the file is opened successfully, it will execute the print statement
It is a write operation in Python. We open an existing file using the given code and
then write on it. The code is given below -
1. file = open('file.txt','w')
2. file.write("Here we write a command")
3. file.write("Hello users of PARUL MIS")
4. file.close()
We can perform any operation on the file externally using the file system which is the
currently opened in Python; hence it is good practice to close the file once all the
operations are done. Earlier use of the close() method can cause the of destroyed some
information that you want to write in your File.
Syntax
1. fileobject.close()
Here we write the program code for the closing method in Python. The code is given
below -
After closing the file, we cannot perform any operation in the file. The file needs to be
properly closed. If any exception occurs while performing some operations in the file
then the program terminates without closing the file.
1. try:
2. fileptr = open("file.txt")
3. # perform file operations
4. finally:
5. fileptr.close()
Syntax:
The advantage of using with statement is that it provides the guarantee to close
the file regardless of how the nested block exits.
It is always suggestible to use the with statement in the case of files because, if
the break, return, or exception occurs in the nested block of code then it
automatically closes the file, we don't need to write the close() function. It
doesn't let the file to corrupt.
Here we write the program code for with statement in Python. The code is given below:
1. with open("file.txt",'r') as f:
2. content = f.read();
3. print(content)
Here we write the program code for with statement in Python. The code is given below
-
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the
file.
a: It will append the existing file. The file pointer is at the end of the file. It creates a
new file if no file exists.
1. # open the file.txt in append mode. Create a new file if no such file exists.
2. fileptr = open("file2.txt", "w")
3.
4. # appending the content to the file
5. fileptr.write('Python is the modern programming language. It is done any kind of pro
gram in shortest way.')
6.
7. # closing the opened the file
8. fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run
it. Then the output is given below -
File2.txt
Python is the modern programming language. It is done any kind of program
in shortest way.
We have opened the file in w mode. The file1.txt file doesn't exist, it created a new file
and we have written the content in the file using the write() function
Program code 2 for Write Method:
Error:
File
"C:\Users\dell\PycharmProjects\pythonProject2\GUIpythonProject\FilesNonGUI\open
File.py", line 3, in <module>
Note: At the end of the block of WITH, file is automatically closed. So, you cannot
access that file outside the WITH block.
Here we write the program code for write method in Python. The code is given below
-
Output:
Now we compile the above code in Python, and after successful compilation, we run
it. Then the output is given below -
Hello coders
Welcome to parul MIS
Here we write the program code for write method in Python. The code is given below
-
1. #open the file.txt in write mode.
2. fileptr = open("file2.txt","a")
3.
4. #appending the content of the file
5. fileptr.write(" Python has an easy syntax and user-friendly interaction.")
6.
7. #closing the opened file
8. fileptr.close()
We can see that the content of the file is appended/modified. We have opened the file
in a mode and it appended the content in the existing file2.txt.
Read(count=number of characters/bytes)
The Python provides the read(no. of characters) method. It returns string. It can read
the data in the text as well as a binary format.
Syntax:
1. fileobj.read(<count>)
Here, the count is the number of bytes/characters to be read from the file starting
from the beginning of the file. If the count is not specified, then it may read the
content of the file until the end.
fileptr = open("demoText.txt","r")
#stores all the data of the file into the variable content
allData=fileptr.read()
print(type(allData)) # prints string object
#prints the content of the file
print(allData)
firstTenBytes = fileptr.read(10)
print(firstTenBytes) #fileptr at end so will not print
anything
fileptr.seek(0) #reset fileptr to first character in the file
firstTenBytes=fileptr.read(10)
print(firstTenBytes)
#prints first 10 characters
#closes the opened file
fileptr.close()
Output:
<class 'str'>
my name is amit
my name is
We have passed count value as ten which means it will read the first ten
characters/bytes from the file.
If we use the following line, then it will print all content of the file.
1. content = fileptr.read()
2. print(content)
Here we give an example of read file using for loop. The code is given below -
1. #open the file.txt in read mode. causes an error if no such file exists.
2. fileptr = open("file2.txt","r")
3. #running a for loop
4. for i in fileptr:
5. print(i) # i contains each line of the file
Output:
Python is the modern day language.
fileptr = open("demoText.txt","r")
#running a for loop
print(fileptr)
for i in fileptr.read():
print(i) # prints character by character
fileptr.seek(0)
for i in fileptr:
print(i) #print line by line
a
m
A
m
i
t
I am Amit
Line1: H
Line2: e
Line3: l
Line4: l
Line5: o
Line6:
Line7: C
Line8: o
Line9: d
Line10: e
Line11: r
Line12: s
Line13:
print("A=",A)
f1 = open('demoText.txt', 'w')
f1.writelines(A)
f1.close()
f1 = open('demoText.txt', 'r')
Lines = f1.read()
print(type(Lines)) #prints string object
print("data=",Lines) #prints all lines in file
Output:
A= ['Hello\n', 'Coders\n', 'Parul MIS\n']
<class 'str'>
data= Hello
Coders
Parul MIS
H
e
l
l
o
C
o
d
e
r
s
P
a
r
u
l
M
I
S
Line2: Coders
Consider the following example which contains a function readline() that reads the
first line of our file "file2.txt" containing three lines. Consider the following example.
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","r");
3. #stores first line of the file into the variable content
4. content = fileptr.readline()
5. content1 = fileptr.readline() #stores second line of the file
6. #prints the content of the file
7. print(content) #prints first line
8. print(content1) #prints second line
9. #closes the opened file
10. fileptr.close()
Output:
print(secondLine)
#closes the opened file
fileptr.close()
oneLine= Hello
Coders
H
e
l
l
o
We called the readline() function two times that's why it read two lines from the
file.That means, if you called readline() function n times in your program, then it read
n number of lines from the file. This is the uses of readline() function in Python.
while(line):
print(line)
line=fileptr.readline()
Python provides readlines() method which is used for the reading lines. It returns the
list of the lines till the end of file(EOF) is reached.
Example 2:
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file.txt","r");
3.
4. #stores all the data of the file into the variable content
5. listOfLines= fileptr.readlines()
6.
7. #prints the content of the file
8. print(listOfLines)
9.
10. #closes the opened file
11. fileptr.close()
Output:
Example 3:
Here we give the example of reading the lines using the readlines() function in Python.
The code is given below -
Output:
Line1: Hello
Line2: Coders
Line3: Parul MIS
x, a and w is the modes of open() function. The uses of these modes are given below
x: it creates a new file with the specified name. It causes an error if a file exists
with the same name.
a: It creates a new file with the specified name if no such file exists. It appends the
content to the file if the file already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It overwrites the
existing file.
Here we give an example for creating a new file in Python. For creates a file, we have
to use the open() method. The code is given below -
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","x")
3. print(fileptr)
4. if fileptr:
5. print("File created successfully")
Output:
Now we compile the above code in Python, and after successful compilation, we run
it. Then the output is given below -
try:
fileptr=open("demoText.txt",'x')
except FileExistsError as error:
print(str(error)+"\nFile already exists!")
1. fileobject.tell()
11.
12. print("After reading, the filepointer is at:",fileptr.tell())
Output:
Output:
For this purpose, the Python provides us the seek() method which enables us to modify
the file pointer position externally. That means, using seek() method we can easily
change the cursor location in the file, from where we want to read or write a file.
Syntax:
Offset (MANDATORY): It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be moved. If it is
set to 0, the beginning of the file is used as the reference position. If it is set to 1, the
current position of the file pointer is used as the reference position. If it is set to
2, the end of the file pointer is used as the reference position.
Here we give the example of how to modifying the pointer position using seek()
method in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run
it. Then the output is given below -
file.seek(0)
print(file.read(1))
print("The pointer position is: ", file.tell())
file.seek(11,0)
print(file.read(1))
print("The pointer position is: ", file.tell())
file.seek(22,0)
print(file.read(1))
print("The pointer position is: ", file.tell())
123456789
abcdefghi
ABCDEFGHI
1
The pointer position is: 1
a
The pointer position is: 12
A
The pointer position is: 23
Python OS module:
Renaming the file
The Python os module enables interaction with the operating system. It comes from
the Python standard utility module. The os module provides a portable way to use the
operating system-dependent functionality in Python. The os module provides the
functions that are involved in file processing operations like renaming, deleting, etc. It
provides us the rename() method to rename the specified file to a new name. Using
the rename() method, we can easily rename the existing File. This method has not any
return value. The syntax to use the rename() method is given below.
Syntax:
1. rename(current-name, new-name)
The first argument is the current file name and the second argument is the modified
name. We can change the file name by passing these two arguments.
1. import os
2.
3. #rename file2.txt to file3.txt
4. os.rename("file2.txt","file3.txt")
from os import *
Syntax:
1. remove(file-name)
1. import os;
2. #deleting the file named file3.txt
3. os.remove("file3.txt")
Method Description
file.close() It closes the opened file. The file once closed, it can't be read or
write anymore.
File.readline([size]) It reads one line from the file and places the file pointer to the
beginning of the new line.
File.readlines([sizehint]) It returns a list containing all the lines of the file. It reads the file until
the EOF occurs using readline() function.
File.seek(offset[,from) It modifies the position of the file pointer to a specified offset with
the specified reference.
File.tell() It returns the current position of the file pointer within the file.
File.truncate([size]) It truncates the file to the optional specified size or the current
cursor position, remaining data will be truncated.