0% found this document useful (0 votes)
15 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)
15 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
You are on page 1/ 9

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/2796647948.py", 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/3772438593.py", 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/1767617266.py 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/Day5.ipynb# 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('file.txt')
except Exception as e:
print(e)
print("File Not found")

[Errno 2] No such file or directory: 'file.txt'


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/Day5.ipynb# 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\testing.txt","w")
f.close()

Reading file
In [347]:

f = open(r"C:\Users\chinu\Desktop\testing.txt","r")
print(f.read())
print(f.read())
f.close()

Hello
Coding

In [348]:

f = open(r"C:\Users\chinu\Desktop\testing.txt","r")
for i in f:
print(i)
f.close()

Hello

Coding

In [351]:

f = open(r"C:\Users\chinu\Desktop\testing.txt","r")
print(f.read(10))
f.close()

Hello
Cod

In [353]:

f = open(r"C:\Users\chinu\Desktop\testing.txt","r")
print(f.readline())
print(f.readline())
f.close()

Hello

Coding

In [35]:

f = open(r"C:\Users\chinu\Desktop\testing.txt","r")
print(f.readlines())
f.close()

['Hello \n', 'Coding']

localhost:8888/notebooks/Python Bootcamp/Day5.ipynb# 3/9


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

In [357]:

fs = open(r"C:\Users\chinu\Desktop\testing.txt","r")
print(fs.readlines())
for i in fs:
print(i)

['Hello \n', 'Coding']

In [358]:

fp = open(r"C:\Users\chinu\Desktop\testing.txt")
print(fp.read())

Hello
Coding

Writing file
In [361]:

fo = open(r"C:\Users\chinu\Desktop\testing.txt","w")
fo.write("Thanks for your support\n") # writing in the file
fo.write("Congrats")
f.close()

In [362]:

fp = open(r"C:\Users\chinu\Desktop\testing.txt")
print(fp.read())
f.close()

Thanks for your support


Congrats

In [365]:

fo = open(r"C:\Users\chinu\Desktop\testing.txt","w")
fo.writelines("Welcome to Coding clubs\nThanks for your support\n ") # writing in the file
fo.close()

In [366]:

fp = open(r"C:\Users\chinu\Desktop\testing.txt")
print(fp.read())
fp.close()

Welcome to Coding clubs


Thanks for your support

Appending data into file


In [367]:

fo = open(r"C:\Users\chinu\Desktop\testing.txt","a")
skills = ["python\n","Java\n","ML\n"]
fo.writelines(skills)
fo.close()

In [368]:

fp = open(r"C:\Users\chinu\Desktop\testing.txt")
print(fp.read())
f.close()

Welcome to Coding clubs


Thanks for your support
python
Java
ML

In [369]:

with open(r"C:\Users\chinu\Desktop\testing.txt","r") as fp:


print(fp.read())

Welcome to Coding clubs


Thanks for your support
python
Java
ML

localhost:8888/notebooks/Python Bootcamp/Day5.ipynb# 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\testing.txt","r") as fp:
data = fp.readlines()
for line in data:
word = line.split()
print(word)

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


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

In [372]:

import os
print(os.getcwd()) #current working directory
print(os.listdir()) # list of directories and files
print(os.mkdir("test")) # create directory
print(os.listdir())

C:\Users\chinu\Python Bootcamp
['.ipynb_checkpoints', 'Day2.ipynb', 'Day3.ipynb', 'Day4.ipynb', 'Day5.ipynb', 'Day6.ipynb', 'IPL_dataset_anaysis.ipynb',
'IPL_matches_dataset.csv', 'PythonBootcamp (2).ipynb', 'pythonbootcamp.py', 'simplemaths.py', 'test', '__pycache__']

---------------------------------------------------------------------------
FileExistsError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_3932/2659769821.py in <module>
2 print(os.getcwd()) #current working directory
3 print(os.listdir()) # list of directories and files
----> 4 print(os.mkdir("test")) # create directory
5 print(os.listdir())

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 = re.search("high",string)
print(x)
if(x):
print("Found")
else:
print("Not found")

<re.Match object; span=(10, 14), match='high'>


Found

In [67]:

import re
string = "Python is high level language"
x = re.search("high",string)
print(x.start())
print(x.end())

10
14

In [69]:

import re
string = "Python is high level language"
x = re.split('\s',string)
print(x)

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

In [99]:

import re
string = "Python is high level language"
x = re.findall('i',string)
print(x)

['i', 'i']

localhost:8888/notebooks/Python Bootcamp/Day5.ipynb# 5/9


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

In [101]:

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

<re.Match object; span=(0, 6), match='Python'>


Found

In [110]:

import re
string = "Python is high level language"
string1 = "Python"
x = re.fullmatch('Python',string)
y = re.fullmatch('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 = re.compile(string)
print(p.findall("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 = re.findall("^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 = re.findall("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/Day5.ipynb# 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 = re.findall("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 = re.search("P.t",string)
print(x)
print(y)

<re.Match object; span=(0, 3), match='Pyt'>


<re.Match 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 = re.search(".",string)
y = re.search("\.",string)
print(x)
print(x.start())
print(y.start())

<re.Match 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 = re.findall("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 = re.findall("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 = re.findall("[A-Z]",string)
print(x)
y = re.findall("[^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/Day5.ipynb# 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 = re.findall("is{0,10}",string)
print(x)
y = re.findall("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 = re.findall("(is)",string)
print(x)
y = re.findall("(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 = re.findall("\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'
re.findall(p1,str)

Out[319]:

['Python']

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

In [335]:

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

['3']

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

In [334]:

import re
string = "Python is high level language."
x = re.findall("\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/Day5.ipynb# 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 = re.findall("\s",string)
print(x)

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

\S - Matches any non-whitespace character

In [288]:

import re
string = "Python is high level language."
x = re.findall("\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 = re.findall("\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 = re.findall("\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 = re.findall("language.\Z",string)
print(x)

['language.']

In [ ]:

localhost:8888/notebooks/Python Bootcamp/Day5.ipynb# 9/9

You might also like