Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

File Handling

In [ ]: """
file: is a medium to store a data/contents on hard drive so we can retrieve them as pe
operations over it.
Operations we perform on file:
- Create
- Open
- Update
- Read
- Write
- delete
- close
=====================================
In python, we have open function to deal with these all operation
================
# Create a file: use open function
In python, file handling default supports .txt means text mode
It can also handle other files like csv,image, excel and so on
==================================
open('test_1.txt',mode='w')
# here test_1.txt is a file name and 'w' is a write mode
# used to create a new file
========================
How to check different modes and its info
----------------------

Open file and return a stream. Raise OSError upon failure.

file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file
is opened. It defaults to 'r' which means open for reading in text
mode. Other common values are 'w' for writing (truncating the file if
it already exists), 'x' for creating and writing to a new file, and
'a' for appending (which on some Unix systems, means that all writes
append to the end of the file regardless of the current seek position).
In text mode, if encoding is not specified the encoding used is platform
dependent: locale.getpreferredencoding(False) is called to get the
current locale encoding. (For reading and writing raw bytes use binary
mode and leave encoding unspecified.) The available modes are:

========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
-------------------------------
open('test_1.txt','w')
# it will create a new file and if file is already present
# with contents then it will truncate the contents
# we can also add new contents every time using this mode
------------------------
if i want to create a file at any other location on my machine then??

open('C:\\Users\hakim\OneDrive\Desktop\Project\project_data_science.txt','w')
---------------------------
Now read a file from other location
---------------------
f = open('C:\\Users\hakim\OneDrive\Desktop\\New Text Document.txt')
print(f.read())
=============================
second mode for file creation is 'x' mode
Exclusive mode:
if file is nt present then create that file
it its present then error:FileExistsError
---> it is used to create a file only ones.
--------------------

# file is already present so it'll give FileExistsError
open('test_1.txt','x')
--------------------------
# file is not present to it will create a new file
open('test2.txt','x')
# if u execute this once again u will get:FileExistsError
-----------------------------------------
# Third mode is 'a' append mode
==> if file is nt present then create and perform write operation,
and if file is present(which has some text)
then we can append the contents
------------------
open('test3.txt','a')
-------------------------
Let's check the properties of the present file
f = open('test3.txt','w+')
print(f.name)
print(f.mode)
print(f.writable())
print(f.readable())
----------------------------
"""
In [ ]: """
Write Operation:
modes present: w,a,x
to perform write opration we have options:
1. write
2. writeline
--------------------------------
#write
----------------
# w
f = open('test_1.txt','w')
f.write('Hello, \nHow r u? \nI am new here')
f.write('\nPlease help me....')
# u must hv to pass a str
f.write(100)
# TypeError: write() argument must be str, not int
-------------------------------
# w
f = open('test_1.txt','w')
# in writelines we must have to supply an iterable
f.writelines(['10\n','20\n','30'])
f.writelines(('\nSuresh','\nRamesh','\nMahesh'))
f.writelines('\nPython')
===========================
what is difference between write and writelines
In write we can only supply string,iterables other than string are
nt allowed

But in writelines we can supply any iterable
======================================================
READ Operation:
we have 3 options is this:
read(): will read all the contents from file
readline()
readlines()
===================================
f = open('test3.txt')
#print(f.read()) #will read everything

# nw read starting 10 blocks
#print(f.read())
#print('remaining:',f.read(10))
##########################
# if i want to fetch python directly
#print(type(f.read()))
#print(f.read().find('Python'))
#print(f.read()[3:9])
ls = f.read().split()
print(ls)
for i in ls:
if i == 'Python':
print(i)
==========================================
# Now fetch only numbers from a file test2.txt
f = open('test2.txt')
#data = f.read().split(':')
#print(data)
data = f.readlines()
print(data)
num = []
#print('No.of lines:',len(f.readlines()))
for i in data:
#print(i)
#print(i.split(':')[-1])
num.append(i.split(':')[-1])
print('Number list:',num)
print(num[1])
==================================
f = open('test2.txt')
f2 = open('C:\\Users\hakim\OneDrive\Desktop\\xyz.txt','a')
#data = f.read().split(':')
#print(data)
data = f.readlines()
print(data)
#print('No.of lines:',len(f.readlines()))
for i in data:
#print(i)
f2.write(i.split(':')[-1])

"""
In [ ]: """
Read operation:
read(): read all file
readline(): one line at a time
readlines(): read all the lines as a list of string
"""
"""
seek(): bring ur cursor to a particular block
and tell() function: wil tell u current position
-----------------------------------
f = open('test3.txt')
print(f.tell())
print(f.read(7))
print(f.tell())
print(f.read())
print(f.tell())
=================================
f = open('test3.txt')
f.seek(15) #bring a cursor to 15 block
print(f.read(15))
print(f.tell())
==================================
# How to read an image file and how to write
----------------------------
# to read a binary file use r+b mode/ rb mode
# read in binary
f = open('ds.jpg',mode='r+b')
#print(f.read())
data =f.read()

#write to binary
a = open('new.png',mode='w+b')
a.write(data)
------------------------------------
# Perform Read write operations over csv file
#-------------------
# Create a CSV file
# directly we can create
f = open('exam.csv','w')
#------------------
but in order to deal with csv properly we need cvs module
-------------------------------------
import csv
f = open('exam.csv','w',newline='')
w_ob = csv.writer(f)
w_ob.writerow(['Name','Age','Place'])
#lets add data of 2 student
w_ob.writerow(['A',23,'Pune'])
w_ob.writerow(['B',30,'Place'])
==============================
import csv
f = open('exam.csv','w',newline='')
w_ob = csv.writer(f)
w_ob.writerow(['Name','Age','Place'])
#lets add data of n student
n = int(input('Enter no. of student:'))
for i in range(n):
nm = input('Enter your name:')
age = int(input('ENter Age:'))
pl = input('Enter place:')
w_ob.writerow([nm,age,pl])

==========================================
import csv
import random
f = open('exam.csv','w',newline='')
w_ob = csv.writer(f)
w_ob.writerow(['Age','new_feature'])
#lets add data of n student
n = int(input('Enter no. of student:'))
for i in range(n):
n_val = random.randint(6,11)
w_ob.writerow([n_val,n_val*10+20.14])
============================================
# Read operation over CSV
"""
import csv

f = open('exam.csv','r',newline='')
r_ob = csv.reader(f)
print(r_ob)
# listify
print(list(r_ob))
# i want only new_feature entries from this
data = list(r_ob)
print([[j] for i,j in data])

Exceptional Handling
In [ ]: """
Exception: Errors
Example:
NameError
TypeError
ValueError
if u want to check all the errors in python then use
--------------------
import builtins
print(help(builtins))
--------------------------
help('builtins')
"""
"""
Handling of the exceptions:
In order to handle the error we need to deal with 4 blocks
1. try:
\\put a code u want to test
\\ apko lagta hai yaha error ayega

2. except:
\\ if error occurs , control will come here
\\here we can handle exception

3. else: #optional
\\ if no error then come here
\\ if no exception control we come here

4. finally:
\\ i don't care abt exception
\\ either exception occurs or nt i will execute

-------------------------------

print('Pallavi')
print(10/'2') # will give TypeError
print(list(range(6)))
print('End')
-------------------
How to handle above exception:
--------------------------
# lets test single line
try:
#print(10/2) # here no exception so else will get executed
#---------------
print(10/a)# here exception present so it will go to except
# we must have to write/use try except pair
# if we r using try then except must follow it
except:
print('Error occurs')

else:
print('No Error..')

finally:
print('Main zukega nai...')
------------------------------------
# Different ways of handling the exception
try:
print(10/a)
except NameError as msg: #msg is a variable
print('Error:',msg)
print('Please define value of a')
a = int(input('Enter value of a:'))
print(10/a)
print('Hello')
print('GE')
=============================
try:
print(10/0)
except NameError as msg: #msg is a variable
print('Error:',msg)
except ZeroDivisionError as m:
print('Error:',m)
print('GE')
=============
# rather than handling each exception separately will
use combine format
==========================================
try:
#print(10/0)
#print(10/a)
#print('10'/'20')
d = {1:200}
print(d[20])
except (NameError,ZeroDivisionError,TypeError) as msg: #msg is a variable
print('Error:',msg)
# if we miss any of the exception
# need to handle that , then go for default exception
except: # default exception
print('Error occurs')
==============================
try:
print(10/0)
#print(10/a)
#print('10'/'20')
#d = {1:200}
#print(d[20])
except Exception as msg: #msg is a variable
print('Error:',msg)
---------------------------------------------
"""
In [ ]: """
In case of exception till now we have seen built-in exceptions
Now we are going to look at User defined exceptions
==========================================
"""
"""
1. raise
Python raise Keyword is used to raise exceptions or errors. The raise keyword raises a
handler so that it can be handled further up the call stack.
syntax:
raise Exception('msg')
=============================
# if age is >18 then ok, otherwise exception
age = 3
if age > 18:
print('You are allowed')
else:
raise Exception('Only Adults allowed 18+')
===========================================
try:
raise Exception
except:
print('Handled exception')
=====================================
num = 10

raise ValueError('Value must be in int format')
=============================================
s = 'apple'
try:
num = int(s)
except ValueError:
raise ValueError("String can't be changed into integer")
==========================================================
2. assert
-------------------
#assert <condition>
assert True # will nt generate an exception
assert False # it will generate Assertion Error
# Syntax: assert <condition>,'error_msg'

Example:
assert False,'Error occurs'
----------------------\
pin = 1234 # Database pin
n_pin = 4545 # user_entered
assert pin == n_pin,'Wrong pin entered'
=====================================
pin = 1234 # Database pin
n_pin = 4545 # user_entered
try:
assert pin == n_pin,'Wrong pin entered'
except AssertionError:
n = int(input('Enter new pin:'))
print('Write further logic')
=================================
# How to create ur own exception class
class Check_18(Exception): # as a exception class
pass
age = 7
if age < 18:
raise Check_18('18+ required')
"""

You might also like