SlideShare a Scribd company logo
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
Python Programming - Files & Exceptions
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
Python Programming - Files & Exceptions
Python Programming - Files & Exceptions
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”
Ad

More Related Content

What's hot (20)

Decision Structures and Boolean Logic
Decision Structures and Boolean LogicDecision Structures and Boolean Logic
Decision Structures and Boolean Logic
Munazza-Mah-Jabeen
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
Binay Kumar Ray
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Kamal Acharya
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
baabtra.com - No. 1 supplier of quality freshers
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
ARVIND PANDE
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Operator Overloading In Python
Operator Overloading In PythonOperator Overloading In Python
Operator Overloading In Python
Simplilearn
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
Karin Lagesen
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
Praveen M Jigajinni
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
Nicole Ryan
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
pandas - Python Data Analysis
pandas - Python Data Analysispandas - Python Data Analysis
pandas - Python Data Analysis
Andrew Henshaw
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
Venkata.Manish Reddy
 
Data types in php
Data types in phpData types in php
Data types in php
ilakkiya
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
Mohd Sajjad
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 
Decision Structures and Boolean Logic
Decision Structures and Boolean LogicDecision Structures and Boolean Logic
Decision Structures and Boolean Logic
Munazza-Mah-Jabeen
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
ARVIND PANDE
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Operator Overloading In Python
Operator Overloading In PythonOperator Overloading In Python
Operator Overloading In Python
Simplilearn
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
Karin Lagesen
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
Nicole Ryan
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
pandas - Python Data Analysis
pandas - Python Data Analysispandas - Python Data Analysis
pandas - Python Data Analysis
Andrew Henshaw
 
Data types in php
Data types in phpData types in php
Data types in php
ilakkiya
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
Mohd Sajjad
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 

Similar to Python Programming - Files & Exceptions (20)

Chapter 11
Chapter 11Chapter 11
Chapter 11
Terry Yoast
 
UNIT –5.pptxpython for engineering students
UNIT –5.pptxpython for engineering studentsUNIT –5.pptxpython for engineering students
UNIT –5.pptxpython for engineering students
SabarigiriVason
 
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
Srinivas Narasegouda
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
sulekha24
 
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
Ananta Lamichhane
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
Inzamam Baig
 
Qtp launch
Qtp launchQtp launch
Qtp launch
G C Reddy Technologies
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
nishant874609
 
File handling for reference class 12.pptx
File handling for reference class 12.pptxFile handling for reference class 12.pptx
File handling for reference class 12.pptx
PreeTVithule1
 
File handling
File handlingFile handling
File handling
Swarup Kumar Boro
 
23CS101T PSPP python program - UNIT 5.pdf
23CS101T PSPP python program - UNIT 5.pdf23CS101T PSPP python program - UNIT 5.pdf
23CS101T PSPP python program - UNIT 5.pdf
RajeshThanikachalam
 
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
Master of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdfMaster of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdf
Krrai1
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15
Vishal Dutt
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
Python File Handling52616416416 ppt.pptx
Python File Handling52616416416 ppt.pptxPython File Handling52616416416 ppt.pptx
Python File Handling52616416416 ppt.pptx
saiwww3841k
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
TAlha MAlik
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
study material
 
UNIT –5.pptxpython for engineering students
UNIT –5.pptxpython for engineering studentsUNIT –5.pptxpython for engineering students
UNIT –5.pptxpython for engineering students
SabarigiriVason
 
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
Srinivas Narasegouda
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
sulekha24
 
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
Ananta Lamichhane
 
File handling for reference class 12.pptx
File handling for reference class 12.pptxFile handling for reference class 12.pptx
File handling for reference class 12.pptx
PreeTVithule1
 
23CS101T PSPP python program - UNIT 5.pdf
23CS101T PSPP python program - UNIT 5.pdf23CS101T PSPP python program - UNIT 5.pdf
23CS101T PSPP python program - UNIT 5.pdf
RajeshThanikachalam
 
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
Master of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdfMaster of computer application python programming unit 3.pdf
Master of computer application python programming unit 3.pdf
Krrai1
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15
Vishal Dutt
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
Python File Handling52616416416 ppt.pptx
Python File Handling52616416416 ppt.pptxPython File Handling52616416416 ppt.pptx
Python File Handling52616416416 ppt.pptx
saiwww3841k
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
TAlha MAlik
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
study material
 
Ad

Recently uploaded (20)

WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Innovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at allInnovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at all
ayeshakanwal75
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025
younisnoman75
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
Imma Valls Bernaus
 
Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025
fs4635986
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Implementing promises with typescripts, step by step
Implementing promises with typescripts, step by stepImplementing promises with typescripts, step by step
Implementing promises with typescripts, step by step
Ran Wahle
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game DevelopmentBest Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Juego Studios
 
Creating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdfCreating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdf
Applitools
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Innovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at allInnovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at all
ayeshakanwal75
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025
younisnoman75
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
Imma Valls Bernaus
 
Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025
fs4635986
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Implementing promises with typescripts, step by step
Implementing promises with typescripts, step by stepImplementing promises with typescripts, step by step
Implementing promises with typescripts, step by step
Ran Wahle
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game DevelopmentBest Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Juego Studios
 
Creating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdfCreating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdf
Applitools
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Ad

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
  • 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
  • 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”