Unit3 File Handling
Unit3 File Handling
Errors ¶
In [1]:
print("Hello")
Hello
In [2]:
print"Hello" # Error
In [3]:
try:
print"Hello"
except:
print("Invalid print statement")
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
In [6]:
try:
print(Hello)
except:
print("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")
In [ ]:
try:
list = [10,20,30,40]
print(list[5])
except Exception as e:
print(e)
In [16]:
try:
list = [10,20,30,40]
print(list[5])
except IndexError as i:
print(i)
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")
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
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% ")
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()
In [357]:
fs = open(r"C:\Users\chinu\Desktop\testing.txt","r")
print(fs.readlines())
for i in fs:
print(i)
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()
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()
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()
In [369]:
In [370]:
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
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")
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)
In [99]:
import re
string = "Python is high level language"
x = re.findall('i',string)
print(x)
['i', 'i']
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")
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
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")
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'")
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)
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())
In [174]:
import re
string = "Python is high level language."
x = re.findall("le*",string)
print(x)
In [175]:
import re
string = "Python is high level language."
x = re.findall("le+",string)
print(x)
['le']
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', '.']
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']
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']
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']
In [335]:
import re
string = "Python is high level language.3"
x = re.findall("\d",string)
print(x)
['3']
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', '.']
In [268]:
import re
string = "Python is high level language."
x = re.findall("\s",string)
print(x)
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', '.']
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']
In [287]:
import re
string = "Python is high level language."
x = re.findall("\W",string)
print(x)
In [286]:
import re
string = "Python is high level language."
x = re.findall("language.\Z",string)
print(x)
['language.']
In [ ]: