SlideShare a Scribd company logo
1 of 55
UNIT-4
FILES
INTRODUCTION TO FILES
File Handling:
• To store our data permanently for future purpose. For this requirement we
should go for files.
There are 2 types of files:
1. Text Files:
Usually we can use text files to store character data
eg: abc.txt
2. Binary Files:
Usually we can use binary files to store binary data like images,video files,
audio files etc...
• File Built-in functions:
• Before performing any operation (like read or write) on the file, first we
have to open that file. For this we should use Python's inbuilt function
open().
• But at the time of open, we have to specify mode, which represents the
purpose of opening file.
• Syntax :handle = open(file_name, access_mode = 'r’)
(Or)
f = open(filename, mode)
Opening a file example:
f = open("abc.txt","w")
We are opening abc.txt file for writing data.
Closing a File:
• After completing our operations on the file, it is highly recommended to
close the file. For this we have to use close() function.
Syntax : handle.close()
for ex: f.close()
The allowed modes in Python are:
1) r ->open an existing file for read operation. The file pointer is positioned
at the beginning of the file. If the specified file does not exist then we will
get FileNotFoundError. This is default mode.
2) w -> open an existing file for write operation. If the file already contains
some data then it will be overridden. If the specified file is not already
available then this mode will create that file.
3) a -> open an existing file for append operation. It won't override existing
data. If the specified file is not already available then this mode will create a
new file.
4) r+ ->To read and write data into the file. The previous data in the file will not
be deleted. The file pointer is placed at the beginning of the file.
5) w+ ->To write and read data. It will override existing data.
6) a+ ->To append and read data from the file. It wont override existing data.
7) x ->To open a file in exclusive creation mode for write operation. If the file
already exists then we will get FileExistsError.
• Note: All the above modes are applicable for text files. If the above modes
suffixed with 'b' then these represents for binary files.
• Eg: rb, wb, ab, r+b, w+b, a+b, xb
Example program for file properties:
f=open("abc.txt",'w')
print("File Name: ",f.name)
print("File Mode: ",f.mode)
print("Is File Readable: ",f.readable())
print("Is File Writable: ",f.writable())
print("Is File Closed : ",f.closed)
f.close()
print("Is File Closed : ",f.closed)
Output
D:Python_classes>py test.py
File Name: abc.txt
File Mode: w
Is File Readable: False
Is File Writable: True
Is File Closed : False
Is File Closed : True
Various File Attributes (properties) of File Object:
• Once we open a file and we got file object, we can get various details related
to that file by using its properties.
name : Name of opened file
mode : Mode in which the file is opened
Closed : Returns boolean value indicates that file is closed or not
readable() : Returns boolean value indicates that whether file is readable or not
writable() : Returns boolean value indicates that whether file is writable or not.
Example program for file properties:
f=open("abc.txt",'w')
print("File Name: ",f.name)
print("File Mode: ",f.mode)
print("Is File Readable: ",f.readable())
print("Is File Writable: ",f.writable())
print("Is File Closed : ",f.closed)
f.close()
print("Is File Closed : ",f.closed)
Output
D:Python_classes>py test.py
File Name: abc.txt
File Mode: w
Is File Readable: False
Is File Writable: True
Is File Closed : False
Is File Closed : True
File Methods:
File methods are 2 types: 1) Input method 2) Output method
1. Input methods (Reading Character Data from text files):
• We can read character data from text file by using the following read methods.
read()->To read total data from the file
read(n) -> To read 'n' characters from the file
readline()->To read only one line
readlines()->To read all lines into a list
Eg 1: To read total data from the file
f=open("abc.txt",'r')
f.read()
f.close()
Eg 2: To read only first 10 characters:
f=open("abc.txt",'r')
data=f.read(10)
print(data)
f.close()
Output:
sunny
bunny
chinny
vinny
Output:
sunny
bunn
Eg 3: To read data line by line:
f=open("abc.txt",'r')
line1=f.readline()
print(line1,end='')
line2=f.readline()
print(line2,end='')
line3=f.readline()
print(line3,end='')
f.close()
Output:
sunny
bunny
chinny
Eg 4: To read all lines into list:
f=open("abc.txt",'r')
lines=f.readlines()
for line in lines:
print(line,end='')
f.close()
Output
sunny
bunny
chinny
vinny
Eg 5:
f=open("abc.txt","r")
print(f.read(3))
print(f.readline())
print(f.read(4))
print("Remaining data")
print(f.read())
Output
Sun
ny
bunn
Remaining data
chinny
vinny
• 2. Output functions:
• The write() built-in method has the opposite functionality as read() and
readline(). It takes a string that can consist of one or more lines of text data or
a block of bytes and writes the data to the file.
• The writelines() method operates on a list just like readlines(), but takes a list
of strings and writes them out to a file.
• Line termination characters are not inserted between each line, so if desired,
they must be added to the end of each line before writelines() is called.
Note: There is no "writeline()" method since it would be equivalent to calling
write() with a single line string terminated with a NEWLINE character.
Writing data to text files:
We can write character data to the text files by using the following 2
methods.
write(str)
writelines(list of lines)
Eg:
f=open("abcd.txt",'w')
f.write(“Pythonn")
f.write(“Programmingn")
f.write(“Languagen")
print("Data written to the file successfully")
f.close()
abcd.txt:
Python
Programming
Language
• Note: In the above program, data present in the file will be overridden every
time if we run the program. Instead of overriding if we want append
operation then we should open the file as follows.
f=open("abcd.txt",‘a')
list=["sunnyn","bunnyn","vinnyn","chinny"]
f.writelines(list)
print("List of lines written to the file successfully")
f.close()
Note: while writing data by using write() methods, compulsory we have to
provide line separator(n),otherwise total data should be written to a single
line.
abcd.txt:
Python
Programming
Language
sunny
bunny
vinny
chinny
• Standard Files:
• There are generally three standard files that are made available to you when
your program starts.
• These are standard input (usually the keyboard), standard output (buffered
output to the monitor or display),and standard error (unbuffered output to
the screen).
• These files are named stdin, stdout, and stderr and take their names from
the C language.
• Python makes these file handles available to you from the sys module. Once
you import sys, you have access to these files as sys.stdin, sys.stdout, and
sys.stderr.
• The print statement normally outputs to sys.stdout while the raw_input() or
input() built-in function receives its input from sys.stdin.
• sys.* are files, you have to manage the line separation characters.
• The print statement has the built-in feature of automatically adding one to the
end of a string to output.
Exception Handling:
In any programming language there are 3 types of errors are possible.
1. Syntax Errors or Compilation errors
2. Runtime Errors
3.Logical Errors
1.Syntax Errors:
The errors which occurs because of invalid syntax are called syntax errors.
Eg 1:
x=10
if x==10
print("Hello")
SyntaxError: invalid syntax
Eg 2:
print "Hello“
SyntaxError: Missing parentheses in call to 'print’ not valid in python 3.0.
• “Programmer is responsible to correct these syntax errors”. Once all syntax
errors are corrected then only program execution will be started.
2. Runtime Errors: (Also known as exceptions)
• While executing the program if something goes wrong because of end user
input or programming logic or memory problems etc., then we will get
Runtime Errors.
3.Logical Errors: While executing the program nothing goes wrong but if the
expected output doesn’t match with the actual output then its logical error.
• Ex. a=2+3*5 print(a) :Expected output :25
Actual Output : 17
A=(2+3)*5
Eg:1 print(10/0) ==> ZeroDivisionError: division by zero
print(10/"ten") ==> TypeError: unsupported operand type(s) for /: 'int' and
'str’
Eg:2 test.py
x=int(input("Enter Number:"))
print(x)
Output:
D:Python_classes>python test.py
Enter Number: ten
ValueError: invalid literal for int() with base 10: 'ten’.
Note: Exception Handling concept applicable for Runtime errors but not for
syntax errors.
Exception:
• An unwanted and unexpected event that disturbs normal flow of program is
called exception.
Eg:
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
IOError
IndexError
Stmt 1
Stmt 2
Stmt 3
Stmt 4  Exception or Run time error at line 4
Stmt 5
Stmt 6
Stmt 7
Stmt 8
Statements which are executed
Statements which are not executed
• It is highly recommended to handle exceptions.
• The main objective of exception handling is Graceful Termination of the
program.
Exception Handling:
• It does not mean repairing an exception.
• Defining a alternative way to continue rest of the program normally.
Default Exception Handing:
• Every exception in Python is an object. For every exception type the
corresponding classes are available.
• Whenever an exception occurs PVM will create the corresponding exception
object and will check for handling code.
• If handling code is not available then Python interpreter terminates the
program abnormally and prints corresponding exception information to the
console.
• The rest of the program won't be executed.
• Eg:
print("Hello")
print(10/0)
print("Hi")
D:Python_classes>py test.py
Hello
Traceback (most recent call last):
File "test.py", line 2, in <module>
print(10/0)
ZeroDivisionError: division by zero
Exception Handling by using try-except:
• It is highly recommended to handle exceptions.
• The code which may raise exception is called risky code.
• we have to take risky code inside try block. The corresponding handling code
we have to take inside except block i.e., similar to catch block in java.
try-except block:
try:
<Risky Code or error code>
except XXX: //XXX exception
<Handling code/Alternative Code>
Exception without try-except block:
print("Hi ")
print(10/0)
print("Hello")
Exception with try-except block:
print("Hi")
try:
print(10/0)
except ZeroDivisionError:
print(10/2)
print("Hello")
Output:
Hi
ZeroDivisionError: division by zero
Abnormal termination/Non-Graceful Termination
Output:
Hi
5.0
Hello
Ex 2: using try-except block:
try:
f = open("testfile", "w")
f.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")
f.close()
To know exception information:
try:
print(10/0)
except ZeroDivisionError as msg:
print("exception raised and its description is:",msg)
Output:
exception raised and its description is: division by zero
• Here exception data is stored in a exception object i.e. msg.
• In the next statement we are printing the exception object to print the
exception details.
try with multiple except blocks:
try:
stmt 1
stmt 2
-------
except Exception1:
stmt 3
stmt 4
----------
except Exception2:
stmt 5
stmt 6
----------
If try with multiple except blocks available then
based on raised exception the corresponding
except block will be executed.
• Example program for try with multiple except blocks:
prog.py
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except ZeroDivisionError :
print("Can't Divide with Zero")
except ValueError:
print("please provide int value only")
D:Python_classes>prog test.py
Enter First Number: 10
Enter Second Number: 2
5.0
-----------------------------------------------------
D:Python_classes>prog test.py
Enter First Number: 10
Enter Second Number: 0
Can't Divide with Zero
-----------------------------------------------------
D:Python_classes>prog test.py
Enter First Number: ten
Enter Second Number: 0
please provide int value only
Eg: 2
prog.py
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except ArithmeticError :
print("ArithmeticError")
except ZeroDivisionError:
print("ZeroDivisionError")
D:Python_classes>prog test.py
Enter First Number: 10
Enter Second Number: 0
??????????????????????
• Note: If try with multiple except blocks available then the order of
these except blocks is important .
• Python interpreter will always consider from top to bottom until
matched except block identified.
Note: If try with multiple except blocks available then default except block
should be last, otherwise we will get SyntaxError.
Eg:
try:
print(10/0)
except:
print("Default Except")
except ZeroDivisionError:
print("ZeroDivisionError")
SyntaxError: default 'except:' must be last
• The following are various possible combinations of except blocks
1. except ZeroDivisionError:
2. except ZeroDivisionError as msg:
3. except (ZeroDivisionError,ValueError) :
4. except (ZeroDivisionError,ValueError) as msg:
5. except :
finally block:
• It is not recommended to maintain clean up code(Resource Deallocating
Code or Resource Releasing code) inside try block because there is no
guarantee for the execution of every statement inside try block always.
2. It is not recommended to maintain clean up code inside except block,
because if there is no exception then except block won't be executed.
3.To maintain clean up code which should be executed always irrespective of
whether exception raised or not raised and whether exception handled or
not handled. Such type of best place is nothing but finally block.
Syntax:
try:
Risky Code
except:
Handling Code
finally:
Cleanup code
• The speciality of finally block is it will be executed always whether
exception raised or not raised and whether exception handled or
not handled.
Case-1: If there is no exception
try:
print("try")
except:
print("except")
finally:
print("finally")
Output
try
finally
Case-2: If there is an exception raised but
handled:
try:
print("try")
print(10/0)
except ZeroDivisionError:
print("except")
finally:
print("finally")
Output
try
except
Finally
Case-3: If there is an exception raised but not handled:
try:
print("try")
print(10/0)
except NameError:
print("except")
finally:
print("finally")
Output
try
finally
ZeroDivisionError: division by zero(Abnormal Termination)
Note: If try with multiple except blocks available then default except block
should be last,otherwise we will get SyntaxError.
Eg:
try:
print(10/0)
except:
print("Default Except")
except ZeroDivisionError:
print("ZeroDivisionError")
SyntaxError: default 'except:' must be last
Note:
• Whenever we are using os._exit(0) function then Python Virtual Machine
itself will be shutdown.
• In this particular case finally won't be executed.
import os
try:
print("try")
os._exit(0)
except NameError:
print("except")
finally:
print("finally")
Output:
try
-----------------------------------------------------------------
os._exit(0) where 0 represents status code and it
indicates normal termination.
Nested try-except-finally blocks:
• We can take try-except-finally blocks inside try or except or finally blocks.i.e
nesting of try except finally is possible.
try:
----------
try:
-------------
except:
--------------
finally:
--------------
except:
----------
finally:
-----------
Eg:
try:
print("outer try block")
try:
print("Inner try block")
print(10/0)
except ZeroDivisionError:
print("Inner except block")
finally:
print("Inner finally block")
except:
print("outer except block")
finally:
print("outer finally block")
---------------------------------------------
Output:
outer try block
Inner try block
Inner except block
Inner finally block
outer finally block
else block with try-except-finally:
• We can use else block with try-except-finally blocks.else block will be
executed if and only if there are no exceptions inside try block. It is optional.
try:
<Risky Code>
except:
<will be executed if exception inside try>
else:
<will be executed if there is no exception inside try>
finally:
<will be executed whether exception raised or not raised and handled or
not>
Eg:1
try:
print("try")
except:
print("except")
else:
print("else")
finally:
print("finally")
Output:
try
else
finally
Eg: 2
try:
print("try")
print(10/0)
except:
print("except")
else:
print("else")
finally:
print("finally")
Output:
try
except
finally
Various possible combinations of try-except-else-finally:
• Whenever we are writing try block, compulsory we should write except or
finally block i.e without except or finally block we cannot write try block.
• Whenever we are writing except block, compulsory we should write try
block. i.e except without try is always invalid.
• Whenever we are writing finally block, compulsory we should write try
block. i.e finally without try is always invalid.
• We can write multiple except blocks for the same try, but we cannot write
multiple finally blocks for the same try.
• Whenever we are writing else block compulsory except block should be there.
i.e without except we cannot write else block.
• In try-except-else-finally order is important.
• We can define try-except-else-finally inside try, except,else and finally blocks.
i.e nesting of try-except-else-finally is always possible.
Types of Exceptions:
In Python there are 2 types of exceptions are possible.
1. Predefined Exceptions
2. User Defined Exceptions
Predefined Exceptions: (Also known as in-built exceptions)
The exceptions which are raised automatically by Python virtual machine
whenever a particular event occurs, are called pre defined exceptions.
Eg :
ZeroDivisionError.
ValueError
TypeError etc.,
User Defined Exceptions:
• Also known as Customized Exceptions or Programmatic Exceptions.
• To define and raise exceptions explicitly by programmer to indicate that
something goes wrong ,such type of exceptions are called User Defined
Exceptions or Customized Exceptions.
• Programmer is responsible to define these exceptions and Python not having
any idea about these.
• Hence we have to raise explicitly based on our requirement by using "raise"
keyword.
Eg:
InSufficientFundsException
InvalidInputException
InvalidAgeException
Define and Raise Customized Exceptions:
• raise keyword is best suitable for customized exceptions but not for pre
defined exceptions.
• It is used to raise an exception with customized message.
Syntax: raise exceptionname(“exception message”)
Ex:
raise NameError(“Name doesn’t match”)-- not preferred
raise InvalidAgeError(“Age is not valid”) preferred
def status(age):
if age<18:
raise NameError("Invalid age data")
elif age>=18:
print("eligible to vote")
try:
age=int(input("enter a valid age:"))
status(age)
except NameError as e:
print("not eligible to vote:",e)
else:
print("User entered valid data")
finally:
print("Voter Eligibility Test")
Output:
enter a valid age:2
not eligible to vote: Invalid age data
Voter Eligibility Test
---------------------------------------------------------
Output:
enter a valid age:45
eligible to vote
User entered valid data
Voter Eligibility Test
• Every Exception in Python is a class.
• All exception classes are child classes of BaseException i.e., every exception
class extend BaseException either directly or indirectly.
• Hence BaseException acts as root for Python Exception Hierarchy.
• Most of the times being a programmer we have to concentrate Exception and
its child classes.

More Related Content

Similar to Python File functions

Similar to Python File functions (20)

Files in c++
Files in c++Files in c++
Files in c++
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Python - Lecture 9
Python - Lecture 9Python - Lecture 9
Python - Lecture 9
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
Python file handling
Python file handlingPython file handling
Python file handling
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
File handling
File handlingFile handling
File handling
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
Data file handling
Data file handlingData file handling
Data file handling
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Unit-4 PPTs.pptx
Unit-4 PPTs.pptxUnit-4 PPTs.pptx
Unit-4 PPTs.pptx
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
 
file.ppt
file.pptfile.ppt
file.ppt
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 

Recently uploaded

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

Python File functions

  • 2. INTRODUCTION TO FILES File Handling: • To store our data permanently for future purpose. For this requirement we should go for files. There are 2 types of files: 1. Text Files: Usually we can use text files to store character data eg: abc.txt 2. Binary Files: Usually we can use binary files to store binary data like images,video files, audio files etc...
  • 3. • File Built-in functions: • Before performing any operation (like read or write) on the file, first we have to open that file. For this we should use Python's inbuilt function open(). • But at the time of open, we have to specify mode, which represents the purpose of opening file. • Syntax :handle = open(file_name, access_mode = 'r’) (Or) f = open(filename, mode)
  • 4. Opening a file example: f = open("abc.txt","w") We are opening abc.txt file for writing data. Closing a File: • After completing our operations on the file, it is highly recommended to close the file. For this we have to use close() function. Syntax : handle.close() for ex: f.close()
  • 5. The allowed modes in Python are: 1) r ->open an existing file for read operation. The file pointer is positioned at the beginning of the file. If the specified file does not exist then we will get FileNotFoundError. This is default mode. 2) w -> open an existing file for write operation. If the file already contains some data then it will be overridden. If the specified file is not already available then this mode will create that file. 3) a -> open an existing file for append operation. It won't override existing data. If the specified file is not already available then this mode will create a new file.
  • 6. 4) r+ ->To read and write data into the file. The previous data in the file will not be deleted. The file pointer is placed at the beginning of the file. 5) w+ ->To write and read data. It will override existing data. 6) a+ ->To append and read data from the file. It wont override existing data. 7) x ->To open a file in exclusive creation mode for write operation. If the file already exists then we will get FileExistsError. • Note: All the above modes are applicable for text files. If the above modes suffixed with 'b' then these represents for binary files. • Eg: rb, wb, ab, r+b, w+b, a+b, xb
  • 7. Example program for file properties: f=open("abc.txt",'w') print("File Name: ",f.name) print("File Mode: ",f.mode) print("Is File Readable: ",f.readable()) print("Is File Writable: ",f.writable()) print("Is File Closed : ",f.closed) f.close() print("Is File Closed : ",f.closed) Output D:Python_classes>py test.py File Name: abc.txt File Mode: w Is File Readable: False Is File Writable: True Is File Closed : False Is File Closed : True
  • 8. Various File Attributes (properties) of File Object: • Once we open a file and we got file object, we can get various details related to that file by using its properties. name : Name of opened file mode : Mode in which the file is opened Closed : Returns boolean value indicates that file is closed or not readable() : Returns boolean value indicates that whether file is readable or not writable() : Returns boolean value indicates that whether file is writable or not.
  • 9. Example program for file properties: f=open("abc.txt",'w') print("File Name: ",f.name) print("File Mode: ",f.mode) print("Is File Readable: ",f.readable()) print("Is File Writable: ",f.writable()) print("Is File Closed : ",f.closed) f.close() print("Is File Closed : ",f.closed) Output D:Python_classes>py test.py File Name: abc.txt File Mode: w Is File Readable: False Is File Writable: True Is File Closed : False Is File Closed : True
  • 10. File Methods: File methods are 2 types: 1) Input method 2) Output method 1. Input methods (Reading Character Data from text files): • We can read character data from text file by using the following read methods. read()->To read total data from the file read(n) -> To read 'n' characters from the file readline()->To read only one line readlines()->To read all lines into a list
  • 11. Eg 1: To read total data from the file f=open("abc.txt",'r') f.read() f.close() Eg 2: To read only first 10 characters: f=open("abc.txt",'r') data=f.read(10) print(data) f.close() Output: sunny bunny chinny vinny Output: sunny bunn
  • 12. Eg 3: To read data line by line: f=open("abc.txt",'r') line1=f.readline() print(line1,end='') line2=f.readline() print(line2,end='') line3=f.readline() print(line3,end='') f.close() Output: sunny bunny chinny
  • 13. Eg 4: To read all lines into list: f=open("abc.txt",'r') lines=f.readlines() for line in lines: print(line,end='') f.close() Output sunny bunny chinny vinny
  • 15. • 2. Output functions: • The write() built-in method has the opposite functionality as read() and readline(). It takes a string that can consist of one or more lines of text data or a block of bytes and writes the data to the file. • The writelines() method operates on a list just like readlines(), but takes a list of strings and writes them out to a file. • Line termination characters are not inserted between each line, so if desired, they must be added to the end of each line before writelines() is called. Note: There is no "writeline()" method since it would be equivalent to calling write() with a single line string terminated with a NEWLINE character.
  • 16. Writing data to text files: We can write character data to the text files by using the following 2 methods. write(str) writelines(list of lines) Eg: f=open("abcd.txt",'w') f.write(“Pythonn") f.write(“Programmingn") f.write(“Languagen") print("Data written to the file successfully") f.close() abcd.txt: Python Programming Language
  • 17. • Note: In the above program, data present in the file will be overridden every time if we run the program. Instead of overriding if we want append operation then we should open the file as follows. f=open("abcd.txt",‘a') list=["sunnyn","bunnyn","vinnyn","chinny"] f.writelines(list) print("List of lines written to the file successfully") f.close() Note: while writing data by using write() methods, compulsory we have to provide line separator(n),otherwise total data should be written to a single line. abcd.txt: Python Programming Language sunny bunny vinny chinny
  • 18. • Standard Files: • There are generally three standard files that are made available to you when your program starts. • These are standard input (usually the keyboard), standard output (buffered output to the monitor or display),and standard error (unbuffered output to the screen). • These files are named stdin, stdout, and stderr and take their names from the C language.
  • 19. • Python makes these file handles available to you from the sys module. Once you import sys, you have access to these files as sys.stdin, sys.stdout, and sys.stderr. • The print statement normally outputs to sys.stdout while the raw_input() or input() built-in function receives its input from sys.stdin. • sys.* are files, you have to manage the line separation characters. • The print statement has the built-in feature of automatically adding one to the end of a string to output.
  • 20. Exception Handling: In any programming language there are 3 types of errors are possible. 1. Syntax Errors or Compilation errors 2. Runtime Errors 3.Logical Errors 1.Syntax Errors: The errors which occurs because of invalid syntax are called syntax errors. Eg 1: x=10 if x==10 print("Hello") SyntaxError: invalid syntax
  • 21. Eg 2: print "Hello“ SyntaxError: Missing parentheses in call to 'print’ not valid in python 3.0. • “Programmer is responsible to correct these syntax errors”. Once all syntax errors are corrected then only program execution will be started. 2. Runtime Errors: (Also known as exceptions) • While executing the program if something goes wrong because of end user input or programming logic or memory problems etc., then we will get Runtime Errors. 3.Logical Errors: While executing the program nothing goes wrong but if the expected output doesn’t match with the actual output then its logical error. • Ex. a=2+3*5 print(a) :Expected output :25 Actual Output : 17 A=(2+3)*5
  • 22. Eg:1 print(10/0) ==> ZeroDivisionError: division by zero print(10/"ten") ==> TypeError: unsupported operand type(s) for /: 'int' and 'str’ Eg:2 test.py x=int(input("Enter Number:")) print(x) Output: D:Python_classes>python test.py Enter Number: ten ValueError: invalid literal for int() with base 10: 'ten’.
  • 23. Note: Exception Handling concept applicable for Runtime errors but not for syntax errors. Exception: • An unwanted and unexpected event that disturbs normal flow of program is called exception. Eg: ZeroDivisionError TypeError ValueError FileNotFoundError EOFError IOError IndexError Stmt 1 Stmt 2 Stmt 3 Stmt 4  Exception or Run time error at line 4 Stmt 5 Stmt 6 Stmt 7 Stmt 8 Statements which are executed Statements which are not executed
  • 24. • It is highly recommended to handle exceptions. • The main objective of exception handling is Graceful Termination of the program. Exception Handling: • It does not mean repairing an exception. • Defining a alternative way to continue rest of the program normally.
  • 25. Default Exception Handing: • Every exception in Python is an object. For every exception type the corresponding classes are available. • Whenever an exception occurs PVM will create the corresponding exception object and will check for handling code. • If handling code is not available then Python interpreter terminates the program abnormally and prints corresponding exception information to the console. • The rest of the program won't be executed.
  • 26. • Eg: print("Hello") print(10/0) print("Hi") D:Python_classes>py test.py Hello Traceback (most recent call last): File "test.py", line 2, in <module> print(10/0) ZeroDivisionError: division by zero
  • 27. Exception Handling by using try-except: • It is highly recommended to handle exceptions. • The code which may raise exception is called risky code. • we have to take risky code inside try block. The corresponding handling code we have to take inside except block i.e., similar to catch block in java. try-except block: try: <Risky Code or error code> except XXX: //XXX exception <Handling code/Alternative Code>
  • 28. Exception without try-except block: print("Hi ") print(10/0) print("Hello") Exception with try-except block: print("Hi") try: print(10/0) except ZeroDivisionError: print(10/2) print("Hello") Output: Hi ZeroDivisionError: division by zero Abnormal termination/Non-Graceful Termination Output: Hi 5.0 Hello
  • 29. Ex 2: using try-except block: try: f = open("testfile", "w") f.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") f.close()
  • 30. To know exception information: try: print(10/0) except ZeroDivisionError as msg: print("exception raised and its description is:",msg) Output: exception raised and its description is: division by zero • Here exception data is stored in a exception object i.e. msg. • In the next statement we are printing the exception object to print the exception details.
  • 31. try with multiple except blocks: try: stmt 1 stmt 2 ------- except Exception1: stmt 3 stmt 4 ---------- except Exception2: stmt 5 stmt 6 ---------- If try with multiple except blocks available then based on raised exception the corresponding except block will be executed.
  • 32. • Example program for try with multiple except blocks: prog.py try: x=int(input("Enter First Number: ")) y=int(input("Enter Second Number: ")) print(x/y) except ZeroDivisionError : print("Can't Divide with Zero") except ValueError: print("please provide int value only") D:Python_classes>prog test.py Enter First Number: 10 Enter Second Number: 2 5.0 ----------------------------------------------------- D:Python_classes>prog test.py Enter First Number: 10 Enter Second Number: 0 Can't Divide with Zero ----------------------------------------------------- D:Python_classes>prog test.py Enter First Number: ten Enter Second Number: 0 please provide int value only
  • 33. Eg: 2 prog.py try: x=int(input("Enter First Number: ")) y=int(input("Enter Second Number: ")) print(x/y) except ArithmeticError : print("ArithmeticError") except ZeroDivisionError: print("ZeroDivisionError") D:Python_classes>prog test.py Enter First Number: 10 Enter Second Number: 0 ??????????????????????
  • 34. • Note: If try with multiple except blocks available then the order of these except blocks is important . • Python interpreter will always consider from top to bottom until matched except block identified.
  • 35. Note: If try with multiple except blocks available then default except block should be last, otherwise we will get SyntaxError. Eg: try: print(10/0) except: print("Default Except") except ZeroDivisionError: print("ZeroDivisionError") SyntaxError: default 'except:' must be last
  • 36. • The following are various possible combinations of except blocks 1. except ZeroDivisionError: 2. except ZeroDivisionError as msg: 3. except (ZeroDivisionError,ValueError) : 4. except (ZeroDivisionError,ValueError) as msg: 5. except :
  • 37. finally block: • It is not recommended to maintain clean up code(Resource Deallocating Code or Resource Releasing code) inside try block because there is no guarantee for the execution of every statement inside try block always. 2. It is not recommended to maintain clean up code inside except block, because if there is no exception then except block won't be executed. 3.To maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether exception handled or not handled. Such type of best place is nothing but finally block.
  • 38. Syntax: try: Risky Code except: Handling Code finally: Cleanup code • The speciality of finally block is it will be executed always whether exception raised or not raised and whether exception handled or not handled.
  • 39. Case-1: If there is no exception try: print("try") except: print("except") finally: print("finally") Output try finally Case-2: If there is an exception raised but handled: try: print("try") print(10/0) except ZeroDivisionError: print("except") finally: print("finally") Output try except Finally
  • 40. Case-3: If there is an exception raised but not handled: try: print("try") print(10/0) except NameError: print("except") finally: print("finally") Output try finally ZeroDivisionError: division by zero(Abnormal Termination)
  • 41. Note: If try with multiple except blocks available then default except block should be last,otherwise we will get SyntaxError. Eg: try: print(10/0) except: print("Default Except") except ZeroDivisionError: print("ZeroDivisionError") SyntaxError: default 'except:' must be last
  • 42. Note: • Whenever we are using os._exit(0) function then Python Virtual Machine itself will be shutdown. • In this particular case finally won't be executed. import os try: print("try") os._exit(0) except NameError: print("except") finally: print("finally") Output: try ----------------------------------------------------------------- os._exit(0) where 0 represents status code and it indicates normal termination.
  • 43. Nested try-except-finally blocks: • We can take try-except-finally blocks inside try or except or finally blocks.i.e nesting of try except finally is possible. try: ---------- try: ------------- except: -------------- finally: -------------- except: ---------- finally: -----------
  • 44. Eg: try: print("outer try block") try: print("Inner try block") print(10/0) except ZeroDivisionError: print("Inner except block") finally: print("Inner finally block") except: print("outer except block") finally: print("outer finally block") --------------------------------------------- Output: outer try block Inner try block Inner except block Inner finally block outer finally block
  • 45. else block with try-except-finally: • We can use else block with try-except-finally blocks.else block will be executed if and only if there are no exceptions inside try block. It is optional. try: <Risky Code> except: <will be executed if exception inside try> else: <will be executed if there is no exception inside try> finally: <will be executed whether exception raised or not raised and handled or not>
  • 47. Various possible combinations of try-except-else-finally: • Whenever we are writing try block, compulsory we should write except or finally block i.e without except or finally block we cannot write try block. • Whenever we are writing except block, compulsory we should write try block. i.e except without try is always invalid. • Whenever we are writing finally block, compulsory we should write try block. i.e finally without try is always invalid. • We can write multiple except blocks for the same try, but we cannot write multiple finally blocks for the same try.
  • 48. • Whenever we are writing else block compulsory except block should be there. i.e without except we cannot write else block. • In try-except-else-finally order is important. • We can define try-except-else-finally inside try, except,else and finally blocks. i.e nesting of try-except-else-finally is always possible.
  • 49. Types of Exceptions: In Python there are 2 types of exceptions are possible. 1. Predefined Exceptions 2. User Defined Exceptions Predefined Exceptions: (Also known as in-built exceptions) The exceptions which are raised automatically by Python virtual machine whenever a particular event occurs, are called pre defined exceptions. Eg : ZeroDivisionError. ValueError TypeError etc.,
  • 50. User Defined Exceptions: • Also known as Customized Exceptions or Programmatic Exceptions. • To define and raise exceptions explicitly by programmer to indicate that something goes wrong ,such type of exceptions are called User Defined Exceptions or Customized Exceptions. • Programmer is responsible to define these exceptions and Python not having any idea about these. • Hence we have to raise explicitly based on our requirement by using "raise" keyword.
  • 52. Define and Raise Customized Exceptions: • raise keyword is best suitable for customized exceptions but not for pre defined exceptions. • It is used to raise an exception with customized message. Syntax: raise exceptionname(“exception message”) Ex: raise NameError(“Name doesn’t match”)-- not preferred raise InvalidAgeError(“Age is not valid”) preferred
  • 53. def status(age): if age<18: raise NameError("Invalid age data") elif age>=18: print("eligible to vote") try: age=int(input("enter a valid age:")) status(age) except NameError as e: print("not eligible to vote:",e) else: print("User entered valid data") finally: print("Voter Eligibility Test") Output: enter a valid age:2 not eligible to vote: Invalid age data Voter Eligibility Test --------------------------------------------------------- Output: enter a valid age:45 eligible to vote User entered valid data Voter Eligibility Test
  • 54.
  • 55. • Every Exception in Python is a class. • All exception classes are child classes of BaseException i.e., every exception class extend BaseException either directly or indirectly. • Hence BaseException acts as root for Python Exception Hierarchy. • Most of the times being a programmer we have to concentrate Exception and its child classes.