SlideShare a Scribd company logo
1 of 32
Download to read offline
CS.QIAU - Winter 2020
PYTHONFiles & Exceptions- Session 7
Omid AmirGhiasvand
Programming
File
▸ A file is a common storage unit in a computer.
▸ programs can read from a file or write into a file.
▸ Serious program use file or database to save state.
▸ File Extension
▸ determine which program will be associated with the file.
▸ .docx or .txt or .csv or .tsv or .json
▸ .mp3 or .mkv
▸ .exe or .bin or .dmg or .tar.gz
▸ Type of file supported by Python:
▸ Text file
▸ Binary file
Creating or Opening Text File
file_handler = open(file_name, mode)
File handler
object Built-in
function
File Handler Object
▸ The open() function return a file handler object for the file name.
▸ The first argument is a string containing the path and file name to be
opened.
▸ The second argument is also a string describing the way in which the file will
be used.
Access Mode
PATH
▸ The first argument is a string containing the path and file name to be
opened.
▸ Absolute/fully qualified path:
▸ Relative path:
“C:UserAmirDocumentscontact.csv”
“.datasample.csv”
“..datasample.csv”
“....datasample.csv”
Current
Directory
Parent
Directory
2 Directories
above the current
Directory
Windows use  and Mac OS and Linux use /
Access Mode
▸ The access mode argument is optional.
▸ ‘r’ will be used if omitted.
▸ Useful Access Modes
Mode Description
‘r’ Opens the file in read only mode.
‘w’ Opens the file for writing. If the file already exists then it will get overwritten. If the file does’t exist it creates a new file
‘a’ Opens the file for appending data at the end of the file automatically. If the file does’t exist it creates a new file
‘r+’ Opens the file for both reading and writing.
‘w+’ Opens the file for reading and writing. If the file already exists then it will get overwritten. If the file does’t exist it creates a new file
‘a+’ Opens the file for reading and appending. If a file already exists, the data is appended. If the file does’t exist it creates a new file.
‘x’ Creates a new file. If the file already exists, the operation fails
▸ Opening files consume system resources.
▸ To save resource it is important to close the file once processing is
completed.
▸ If you do not explicitly close a file, Python’s garbage collector will eventually
destroy the object and close the opened file for you, but the file may have
stayed open for a while.
Closing the File
file_handler.close()
Memory Leak
sample.txt
relative path
current folder
Access
mode
read 1
line and
print it
test.txt in
data folder
relative path in
data folder
With Statement To Open and Close Files
with open(file_name, mode) as file_handler :
statement-1
statement-2
statement-3
Keyword
Programmer
DefinedKeyword
We don’t have to close the file manually.
You can use the
file in this block.
▸ File handler methods
Working With File
Method Syntax Description
read() file_handler.read() used to read the contents of a file
readline() file_handler.readline() used to read a single line in file.
readlines() file_handler.readlines() used to read all the lines of a file as list items.
write() file_handler.write() will write the contents of the string to the file. Add n to add newline
writelines() file_handler.writelines() will write a sequence of strings to the file.
tell() file_handler.tell() returns an integer giving the file handler’s current position within the file
seek() file_handler.seek(offset) is used to change the file handler’s position.
read line 1
read line 2
read line 3
Original file has 1
empty line between
paragraphs and we add
one more
remove the
extra new line
split() method split
the text into a list
separated by dot
2 dimensionals
list
It’s one item - A
sentence
dot delimiter
It’s a list - list of
sentences
remove white
space from beginning
and end of “line”
▸ Lightweight text-based data-interchange. Commonly used for
transmitting data in web applications.
▸ http/https protocol
JavaScript Object Notation - JSON
Client Server
http request
http response
Client/Server Architecture
▸ Key-value pair
▸ value data type : string, object, number, boolean and list
JSON Format
{
"article_link": “https://www.huffingtonpost.com/entry/versace-black-code_us_5861fbefe4b0de3a08f600d5",
“headline": "former versace store clerk sues over secret 'black code' for minority shoppers",
"is_sarcastic": 0
}
key value
json file
key
json
value
load() method
load a json file
jsonlines
this file is not a
valid json file
here each
line is a string
Total
number of
json object
loads()
method load a
string line that is a
json in nature
add json
into a list
▸ There are at least two distinguishable kinds of errors
▸ Syntax Errors
▸ Exceptions
▸ Even if a statement or expression is syntactically correct, it may cause an error
when an attempt is made to execute it. An exception is an unwanted event that
interrupts the normal flow of the program.
▸ User Defined
▸ Built-in
▸ Exception Handling
▸ Handling of exception ensures that the flow of the program does not get
interrupted when an exception occurs which is done by trapping run-time errors.
Exception
Error in Run-time
▸ To handle the exception we can use try-except-finally block.
Exception Handling
try :
statement-1
statement-2
statement-3
except ExceptionName-1
statement-4
except ExceptionName-2
statement-5
else :
statement-6
finally:
statement-7
depend on which
exception thrown, one of the
except blocks will be
trigger
associated
except block
associated
except block
try block
open
jsonlines file
load string line
as a json
finally block will
execute in all cases
else block execute
when no exception
thrown
No exception
exception
the file is in
data folder
newly
created .csv file
camma delimiter
opening two
files in with
we just need
values and not keys
read csv file
each line is a list
each line is a list
import csv
module
“ The Way You Do One Thing Is the Way You Do Everything”

More Related Content

What's hot

Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String Functions
Avanitrambadiya
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 

What's hot (20)

StringTokenizer in java
StringTokenizer in javaStringTokenizer in java
StringTokenizer in java
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Python sqlite3
Python sqlite3Python sqlite3
Python sqlite3
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String Functions
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
 
Linked List
Linked ListLinked List
Linked List
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Python array
Python arrayPython array
Python array
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
UNIT I LINEAR DATA STRUCTURES – LIST
UNIT I 	LINEAR DATA STRUCTURES – LIST 	UNIT I 	LINEAR DATA STRUCTURES – LIST
UNIT I LINEAR DATA STRUCTURES – LIST
 

Similar to Python Programming - Files & Exceptions

Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
TAlha MAlik
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
ANUSUYA S
 

Similar to Python Programming - Files & Exceptions (20)

Chapter 11
Chapter 11Chapter 11
Chapter 11
 
File handling & regular expressions in python programming
File handling & regular expressions in python programmingFile handling & regular expressions in python programming
File handling & regular expressions in python programming
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
 
Module, mixins and file handling in ruby
Module, mixins and file handling in rubyModule, mixins and file handling in ruby
Module, mixins and file handling in ruby
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
 
Qtp launch
Qtp launchQtp launch
Qtp launch
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
 
File handling
File handlingFile handling
File handling
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
 
Files nts
Files ntsFiles nts
Files nts
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Python-files
Python-filesPython-files
Python-files
 
Cis166 final review
Cis166 final reviewCis166 final review
Cis166 final review
 

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 

Python Programming - Files & Exceptions

  • 1. CS.QIAU - Winter 2020 PYTHONFiles & Exceptions- Session 7 Omid AmirGhiasvand Programming
  • 2. File ▸ A file is a common storage unit in a computer. ▸ programs can read from a file or write into a file. ▸ Serious program use file or database to save state. ▸ File Extension ▸ determine which program will be associated with the file. ▸ .docx or .txt or .csv or .tsv or .json ▸ .mp3 or .mkv ▸ .exe or .bin or .dmg or .tar.gz ▸ Type of file supported by Python: ▸ Text file ▸ Binary file
  • 3. Creating or Opening Text File file_handler = open(file_name, mode) File handler object Built-in function
  • 4. File Handler Object ▸ The open() function return a file handler object for the file name. ▸ The first argument is a string containing the path and file name to be opened. ▸ The second argument is also a string describing the way in which the file will be used. Access Mode
  • 5. PATH ▸ The first argument is a string containing the path and file name to be opened. ▸ Absolute/fully qualified path: ▸ Relative path: “C:UserAmirDocumentscontact.csv” “.datasample.csv” “..datasample.csv” “....datasample.csv” Current Directory Parent Directory 2 Directories above the current Directory Windows use and Mac OS and Linux use /
  • 6. Access Mode ▸ The access mode argument is optional. ▸ ‘r’ will be used if omitted. ▸ Useful Access Modes Mode Description ‘r’ Opens the file in read only mode. ‘w’ Opens the file for writing. If the file already exists then it will get overwritten. If the file does’t exist it creates a new file ‘a’ Opens the file for appending data at the end of the file automatically. If the file does’t exist it creates a new file ‘r+’ Opens the file for both reading and writing. ‘w+’ Opens the file for reading and writing. If the file already exists then it will get overwritten. If the file does’t exist it creates a new file ‘a+’ Opens the file for reading and appending. If a file already exists, the data is appended. If the file does’t exist it creates a new file. ‘x’ Creates a new file. If the file already exists, the operation fails
  • 7. ▸ Opening files consume system resources. ▸ To save resource it is important to close the file once processing is completed. ▸ If you do not explicitly close a file, Python’s garbage collector will eventually destroy the object and close the opened file for you, but the file may have stayed open for a while. Closing the File file_handler.close() Memory Leak
  • 9. test.txt in data folder relative path in data folder
  • 10. With Statement To Open and Close Files with open(file_name, mode) as file_handler : statement-1 statement-2 statement-3 Keyword Programmer DefinedKeyword We don’t have to close the file manually. You can use the file in this block.
  • 11. ▸ File handler methods Working With File Method Syntax Description read() file_handler.read() used to read the contents of a file readline() file_handler.readline() used to read a single line in file. readlines() file_handler.readlines() used to read all the lines of a file as list items. write() file_handler.write() will write the contents of the string to the file. Add n to add newline writelines() file_handler.writelines() will write a sequence of strings to the file. tell() file_handler.tell() returns an integer giving the file handler’s current position within the file seek() file_handler.seek(offset) is used to change the file handler’s position.
  • 13. read line 2 read line 3 Original file has 1 empty line between paragraphs and we add one more
  • 15.
  • 16. split() method split the text into a list separated by dot 2 dimensionals list It’s one item - A sentence dot delimiter It’s a list - list of sentences remove white space from beginning and end of “line”
  • 17. ▸ Lightweight text-based data-interchange. Commonly used for transmitting data in web applications. ▸ http/https protocol JavaScript Object Notation - JSON Client Server http request http response Client/Server Architecture
  • 18. ▸ Key-value pair ▸ value data type : string, object, number, boolean and list JSON Format { "article_link": “https://www.huffingtonpost.com/entry/versace-black-code_us_5861fbefe4b0de3a08f600d5", “headline": "former versace store clerk sues over secret 'black code' for minority shoppers", "is_sarcastic": 0 } key value
  • 21. jsonlines this file is not a valid json file
  • 22. here each line is a string
  • 23. Total number of json object loads() method load a string line that is a json in nature add json into a list
  • 24. ▸ There are at least two distinguishable kinds of errors ▸ Syntax Errors ▸ Exceptions ▸ Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. An exception is an unwanted event that interrupts the normal flow of the program. ▸ User Defined ▸ Built-in ▸ Exception Handling ▸ Handling of exception ensures that the flow of the program does not get interrupted when an exception occurs which is done by trapping run-time errors. Exception Error in Run-time
  • 25. ▸ To handle the exception we can use try-except-finally block. Exception Handling try : statement-1 statement-2 statement-3 except ExceptionName-1 statement-4 except ExceptionName-2 statement-5 else : statement-6 finally: statement-7 depend on which exception thrown, one of the except blocks will be trigger associated except block associated except block try block
  • 26.
  • 27.
  • 28. open jsonlines file load string line as a json finally block will execute in all cases else block execute when no exception thrown No exception
  • 29. exception the file is in data folder
  • 30. newly created .csv file camma delimiter opening two files in with we just need values and not keys
  • 31. read csv file each line is a list each line is a list import csv module
  • 32. “ The Way You Do One Thing Is the Way You Do Everything”