File Handling in Python
File Handling in Python
def pattern(n):
#n - outer loop to handle number of rows
for i in range(0, n):
#inner loop to handle number of columns
for j in range(0, i + 1):
#printing stars
print("*", end="")
#ending line after each row
print("\r")
#Driver Code
pattern(5)
2) #Half-Pyramid Pattern Program
def pattern(n):
for i in range(n, -1, -1): # n - Start Value, -1 - end , -1 - step
value
for j in range(0, i + 1):
print("* ", end="")
print("\r")
pattern(5)
2)f=open("D:\HTML\sample.txt", 'r')
print(f.read())
3)f=open("D:\HTML\sample.txt", 'r')
#print(f.read()) # It will display the entire content as it is how we
are saved in the file
#print(f.read(10)) #Using the index position value
#print(f.readline()) # Only one line of content will be displayed
print(f.readlines()) #It will produce the result in list type
4)f=open("D:\HTML\write.txt", 'w')
print(f.write("Next topic Exception Handling in Python"))
5)f=open("D:\HTML\sample.txt", 'r+') # r+ -- read and write
print(f.read())
print(f.write("Next topic Exception Handling in Python\n"))
print(f.write("It is going to handling the errors in coding"))
f.close()
6)f=open("D:\HTML\sample.txt", 'r')
#print(f.read()) # It will display the entire content as it is how we
are saved in the file
#print(f.read(10))
#print(f.readline()) # Only one line of content will be displayed
print(f.readline())
print(f.readline())
Extra Program:
file=open("D:\\PYTHON\\demo.txt", "a")
#a --> write the data into file and append will not erase previous data
print(file.write("\nAppending the data in to file"))
file.close()
4)
file=open("D:\\PYTHON\\demo.txt", "r+")
#r+ --> Read and write the data into file
print(file.read())
print(file.write("File Handling in Python:\nReading a file")) #Write
process will be happen
file.close()
5)
#How to read the csv file using File HAndling Method
r=open("D:\PYTHON\ARUVI ONLINE\write.csv",'r')
print(r.read())
6)
import csv
with open("D:\\PYTHON\\ARUVI ONLINE\\read.csv",'w',
newline='') as file:
writer=csv.writer(file)
writer.writerow(["S.NO", 'NAME', "INVENTOR"])
writer.writerow([1., 'LINUX KERNAL', "LINUS TORVALDS"])
writer.writerow([2., 'WWW', "TIM BERNERS-LEE"])
writer.writerow([3., 'PYTHON', "GUIDO VAN ROSSUM"])
EXCEPTION HANDLING:
1)a='hello'
b=6
try:
result=a+b
print(result)
except:
print("Error occured")
2)
a='hello'
b=6
try:
result=c+b
print(result)
except ZeroDivisionError:
print("Zero is not accepted")
except TypeError:
print("Check datatype of variable")
except NameError:
print("Variable not defined")
3)
a='hello'
b=6
try:
result=c+b
print(result)
except ZeroDivisionError:
print("Zero is not accepted")
except TypeError:
print("Check datatype of variable")
except NameError:
print("Variable not defined")
finally:
print(23+90)