0% found this document useful (0 votes)
31 views9 pages

Unit3 File Handling

File handling
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views9 pages

Unit3 File Handling

File handling
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

08/03/2023, 22:25 Day5 - Jupyter Notebook

Errors and Exception

Errors ¶
In [1]:

print("Hello")

Hello

In [2]:

print"Hello" # Error

File "C:\Users\chinu\AppData\Local\Temp/ipykernel_3932/[Link]", line 1


print"Hello" # Error
^
SyntaxError: invalid syntax

In [3]:

try:
print"Hello"
except:
print("Invalid print statement")

File "C:\Users\chinu\AppData\Local\Temp/ipykernel_3932/[Link]", line 2


print"Hello"
^
SyntaxError: invalid syntax

Exception Handling
In [4]:

print(Hello) # Exception

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_3932/[Link] in <module>
----> 1 print(Hello) # Exception

NameError: name 'Hello' is not defined

In [6]:

try:
print(Hello)
except:
print("variable is not defined.")

variable is not defined.

In [15]:

try:
print(Hello)
except Exception as a:
print(a)
except ValueError as v:
print(v)
finally:
print("Finally block")

name 'Hello' is not defined


Finally block

In [ ]:

try:
list = [10,20,30,40]
print(list[5])

except Exception as e:
print(e)

localhost:8888/notebooks/Python Bootcamp/[Link]# 1/9


08/03/2023, 22:25 Day5 - Jupyter Notebook

In [16]:

try:
list = [10,20,30,40]
print(list[5])

except IndexError as i:
print(i)

list index out of range

In [ ]:

# +-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
| | +-- IndexError
| | +-- KeyError
| +-- MemoryError
| +-- NameError
| | +-- UnboundLocalError
| +-- ReferenceError
| +-- RuntimeError
| | +-- NotImplementedError
| +-- SyntaxError
| | +-- IndentationError
| | +-- TabError
| +-- SystemError
| +-- TypeError
| +-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning

In [17]:

try:
f = open('[Link]')
except Exception as e:
print(e)
print("File Not found")

[Errno 2] No such file or directory: '[Link]'


File Not found

In [20]:

try:
x = float(input("Enter a number :"))
inverse = 1.0/x
except ValueError as v:
print(v)
except ZeroDivisionError as z:
print(z)
finally:
print("The value of x is :",x)

Enter a number :0
float division by zero
The value of x is : 0.0

localhost:8888/notebooks/Python Bootcamp/[Link]# 2/9


08/03/2023, 22:25 Day5 - Jupyter Notebook

User - defined exception


In [26]:

class NewException(Exception):
pass
try:
attendance = int(input("Enter your attendance percentage :"))
if attendance < 75:
raise NewException
else:
print("Your Eligible for EST")
except NewException:
print("Your attendance is below 75% ")

Enter your attendance percentage :78


Your Eligible for EST

File Handling

Creating a file
In [345]:

f = open(r"C:\Users\chinu\Desktop\[Link]","w")
[Link]()

Reading file
In [347]:

f = open(r"C:\Users\chinu\Desktop\[Link]","r")
print([Link]())
print([Link]())
[Link]()

Hello
Coding

In [348]:

f = open(r"C:\Users\chinu\Desktop\[Link]","r")
for i in f:
print(i)
[Link]()

Hello

Coding

In [351]:

f = open(r"C:\Users\chinu\Desktop\[Link]","r")
print([Link](10))
[Link]()

Hello
Cod

In [353]:

f = open(r"C:\Users\chinu\Desktop\[Link]","r")
print([Link]())
print([Link]())
[Link]()

Hello

Coding

In [35]:

f = open(r"C:\Users\chinu\Desktop\[Link]","r")
print([Link]())
[Link]()

['Hello \n', 'Coding']

localhost:8888/notebooks/Python Bootcamp/[Link]# 3/9


08/03/2023, 22:25 Day5 - Jupyter Notebook

In [357]:

fs = open(r"C:\Users\chinu\Desktop\[Link]","r")
print([Link]())
for i in fs:
print(i)

['Hello \n', 'Coding']

In [358]:

fp = open(r"C:\Users\chinu\Desktop\[Link]")
print([Link]())

Hello
Coding

Writing file
In [361]:

fo = open(r"C:\Users\chinu\Desktop\[Link]","w")
[Link]("Thanks for your support\n") # writing in the file
[Link]("Congrats")
[Link]()

In [362]:

fp = open(r"C:\Users\chinu\Desktop\[Link]")
print([Link]())
[Link]()

Thanks for your support


Congrats

In [365]:

fo = open(r"C:\Users\chinu\Desktop\[Link]","w")
[Link]("Welcome to Coding clubs\nThanks for your support\n ") # writing in the file
[Link]()

In [366]:

fp = open(r"C:\Users\chinu\Desktop\[Link]")
print([Link]())
[Link]()

Welcome to Coding clubs


Thanks for your support

Appending data into file


In [367]:

fo = open(r"C:\Users\chinu\Desktop\[Link]","a")
skills = ["python\n","Java\n","ML\n"]
[Link](skills)
[Link]()

In [368]:

fp = open(r"C:\Users\chinu\Desktop\[Link]")
print([Link]())
[Link]()

Welcome to Coding clubs


Thanks for your support
python
Java
ML

In [369]:

with open(r"C:\Users\chinu\Desktop\[Link]","r") as fp:


print([Link]())

Welcome to Coding clubs


Thanks for your support
python
Java
ML

localhost:8888/notebooks/Python Bootcamp/[Link]# 4/9


08/03/2023, 22:25 Day5 - Jupyter Notebook

In [370]:

# printing each word in a file in new line


with open(r"C:\Users\chinu\Desktop\[Link]","r") as fp:
data = [Link]()
for line in data:
word = [Link]()
print(word)

['Welcome', 'to', 'Coding', 'clubs']


['Thanks', 'for', 'your', 'support']
['python']
['Java']
['ML']

In [372]:

import os
print([Link]()) #current working directory
print([Link]()) # list of directories and files
print([Link]("test")) # create directory
print([Link]())

C:\Users\chinu\Python Bootcamp
['.ipynb_checkpoints', '[Link]', '[Link]', '[Link]', '[Link]', '[Link]', 'IPL_dataset_anaysis.ipynb',
'IPL_matches_dataset.csv', 'PythonBootcamp (2).ipynb', '[Link]', '[Link]', 'test', '__pycache__']

---------------------------------------------------------------------------
FileExistsError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_3932/[Link] in <module>
2 print([Link]()) #current working directory
3 print([Link]()) # list of directories and files
----> 4 print([Link]("test")) # create directory
5 print([Link]())

FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'test'

Regular Expressions
Regular expression methods

findall(), search(), match(),fullmatch(),split()

In [63]:

import re
string = "Python is high level language"
x = [Link]("high",string)
print(x)
if(x):
print("Found")
else:
print("Not found")

<[Link] object; span=(10, 14), match='high'>


Found

In [67]:

import re
string = "Python is high level language"
x = [Link]("high",string)
print([Link]())
print([Link]())

10
14

In [69]:

import re
string = "Python is high level language"
x = [Link]('\s',string)
print(x)

['Python', 'is', 'high', 'level', 'language']

In [99]:

import re
string = "Python is high level language"
x = [Link]('i',string)
print(x)

['i', 'i']

localhost:8888/notebooks/Python Bootcamp/[Link]# 5/9


08/03/2023, 22:25 Day5 - Jupyter Notebook

In [101]:

import re
string = "Python is high level language"
x = [Link]('Python',string)
print(x)
if x:
print("Found")
else:
print("Not match")

<[Link] object; span=(0, 6), match='Python'>


Found

In [110]:

import re
string = "Python is high level language"
string1 = "Python"
x = [Link]('Python',string)
y = [Link]('Python',string1)

if x:
print("Found")
else:
print("Not match")
if y:
print("Found")
else:
print("Not match")

Not match
Found

In [122]:

import re
string = "Python is high level language"
p = [Link](string)
print([Link]("Python"))

[]

RegEx : Metacharacters

^ (Caret) - checks if the string starts with a particular string or character

In [125]:

import re
string = "Python is high level language"
x = [Link]("^Python",string)
if x:
print("Yes, Starts with python")
else:
print("String not start with python")

Yes, Starts with python

$ (Dollar) - checks if the string ends with a particular string or character

In [135]:

import re
string = "Python is high level language"
x = [Link]("e$",string)
if x:
print("Yes, String ends with 'e'")
else:
print("String not ends with 'e'")

Yes, String ends with 'e'

localhost:8888/notebooks/Python Bootcamp/[Link]# 6/9


08/03/2023, 22:25 Day5 - Jupyter Notebook

| (Or) - check either/or condition

In [149]:

import re
string = "Python is high level language"
x = [Link]("Python|language",string)
print(x)
if x:
print("Yes , contains Python | language")
else:
print("No match")

['Python', 'language']
Yes , contains Python | language

.(Dot) - used to matches only a single character except for the newline character (\n)

In [333]:

import re
string = "Python is high level language"
x = [Link]("P.t",string)
print(x)
print(y)

<[Link] object; span=(0, 3), match='Pyt'>


<[Link] object; span=(7, 14), match='is high'>

\(Slash) - used to lose the speciality of metacharacters

In [153]:

import re
string = "Python is high level language."
x = [Link](".",string)
y = [Link]("\.",string)
print(x)
print([Link]())
print([Link]())

<[Link] object; span=(0, 1), match='P'>


0
29

*(Star) - returns the zero or more occurrences of a character in a string

In [174]:

import re
string = "Python is high level language."
x = [Link]("le*",string)
print(x)

['le', 'l', 'l']

+(Star) - returns the one or more occurrences of a character in a string

In [175]:

import re
string = "Python is high level language."
x = [Link]("le+",string)
print(x)

['le']

[ ] (brackets) - represent a character class consisting of a set of characters

In [195]:

import re
string = "Python is high level language."
x = [Link]("[A-Z]",string)
print(x)
y = [Link]("[^A-Z]",string)
print(y)

['P']
['y', 't', 'h', 'o', 'n', ' ', 'i', 's', ' ', 'h', 'i', 'g', 'h', ' ', 'l', 'e', 'v', 'e', 'l', ' ', 'l', 'a', 'n', 'g',
'u', 'a', 'g', 'e', '.']

localhost:8888/notebooks/Python Bootcamp/[Link]# 7/9


08/03/2023, 22:25 Day5 - Jupyter Notebook

{} (Curly brackets)-Matches exactly the specified number of occurrences

In [229]:

import re
string = "Python is high level language."
x = [Link]("is{0,10}",string)
print(x)
y = [Link]("is{1,10}",string)
print(y)

['is', 'i']
['is']

( ) (Paranthesis)-used to group sub-patterns

In [234]:

import re
string = "Python is high level language."
x = [Link]("(is)",string)
print(x)
y = [Link]("(high|level)",string)
print(y)

['is']
['high', 'level']

\A- Matches if the string begins with the given character

In [259]:

import re
string = "Python is high level language."
x = [Link]("\APython is",string)
print(x)

['Python is']

\b- Matches if the word begins or ends with the given character

In [319]:

import re
str = "Python is high level language"
p1 = r'\b' + 'Python' + r'\b'
[Link](p1,str)

Out[319]:

['Python']

\d - Matches any decimal digit [0-9]

In [335]:

import re
string = "Python is high level language.3"
x = [Link]("\d",string)
print(x)

['3']

\D - Matches any non-digit character[^0-9]

In [334]:

import re
string = "Python is high level language."
x = [Link]("\D",string)
print(x)

['P', 'y', 't', 'h', 'o', 'n', ' ', 'i', 's', ' ', 'h', 'i', 'g', 'h', ' ', 'l', 'e', 'v', 'e', 'l', ' ', 'l', 'a', 'n',
'g', 'u', 'a', 'g', 'e', '.']

localhost:8888/notebooks/Python Bootcamp/[Link]# 8/9


08/03/2023, 22:25 Day5 - Jupyter Notebook

\s - Matches any whitespace character

In [268]:

import re
string = "Python is high level language."
x = [Link]("\s",string)
print(x)

[' ', ' ', ' ', ' ']

\S - Matches any non-whitespace character

In [288]:

import re
string = "Python is high level language."
x = [Link]("\S",string)
print(x)

['P', 'y', 't', 'h', 'o', 'n', 'i', 's', 'h', 'i', 'g', 'h', 'l', 'e', 'v', 'e', 'l', 'l', 'a', 'n', 'g', 'u', 'a', 'g',
'e', '.']

\w -Matches any alphanumeric character

In [279]:

import re
string = "Python is high level language."
x = [Link]("\w",string)
print(x)

['P', 'y', 't', 'h', 'o', 'n', 'i', 's', 'h', 'i', 'g', 'h', 'l', 'e', 'v', 'e', 'l', 'l', 'a', 'n', 'g', 'u', 'a', 'g',
'e']

\W -Matches any non-alphanumeric character

In [287]:

import re
string = "Python is high level language."
x = [Link]("\W",string)
print(x)

[' ', ' ', ' ', ' ', '.']

\Z - Matches if the string ends with the given regex

In [286]:

import re
string = "Python is high level language."
x = [Link]("language.\Z",string)
print(x)

['language.']

In [ ]:

localhost:8888/notebooks/Python Bootcamp/[Link]# 9/9

You might also like