KEMBAR78
Python Programming - Files & Exceptions | PDF
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”

Python Programming - Files & Exceptions

  • 1.
    CS.QIAU - Winter2020 PYTHONFiles & Exceptions- Session 7 Omid AmirGhiasvand Programming
  • 2.
    File ▸ A fileis 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 OpeningText 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 firstargument 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 ▸ Theaccess 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 filesconsume 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
  • 8.
  • 9.
  • 10.
    With Statement ToOpen 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 handlermethods 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.
  • 12.
  • 13.
    read line 2 readline 3 Original file has 1 empty line between paragraphs and we add one more
  • 14.
  • 16.
    split() method split thetext 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-baseddata-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
  • 19.
  • 20.
  • 21.
    jsonlines this file isnot a valid json file
  • 22.
  • 23.
    Total number of json object loads() methodload a string line that is a json in nature add json into a list
  • 24.
    ▸ There areat 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 handlethe 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
  • 28.
    open jsonlines file load stringline as a json finally block will execute in all cases else block execute when no exception thrown No exception
  • 29.
    exception the file isin data folder
  • 30.
    newly created .csv file cammadelimiter opening two files in with we just need values and not keys
  • 31.
    read csv file eachline is a list each line is a list import csv module
  • 32.
    “ The WayYou Do One Thing Is the Way You Do Everything”