You are on page 1of 64

File Handling

RAM → storage Media (HDD,CD, DVD,pen drive) → called


file
Structure of file storage system
-hierarchical

- File is a sequence of bytes


- Save → file
Types of file
1. Program file → in any programming language
a. Program in particular language
b. Extension tells programming language and some
compiler and interpreter checks before execution
Eg .c means program in c language
.cpp means program in c++
.py means program in Python
c. There is no length
2. Data file → contains data file (in Python)
a. Text file
b. Binary data file
c. CSV file
File handling in a programming language
1. Access a data file through a program
2. program→ other file
3. Process that we can perform on file
a. Read
b. Write → if existing then overwrites, if not existing
then creates
c. Rewrite
d. Append → if not existing creates but if existing then
adds at the end

The operation that we can perform on file are:


1. Create → making the file for the first time
2. Maintain
a. Add → adding the data in an existing file
b. Delete
c. Modify
3. Retrieve
a. Read
b. Query
c. reporting
How to perform any of these task
** open the file
** process the file
** close the file

Difference between text file, binary file

Example of text file


File is a sequence of characters stored on a storage device.
We create a file using text editor software like notepad,
wordpad or Ms word. Each file has an extension .txt
Names of students in 12A
Anjan
Ashutosh
Chaitanya

Example of a binary file


- File has a structure
- Followed in all the records

Fields are : Rollno, Name, Marks, Rank


Rollno Name Marks Rank
1. A 90 3
2 B 89 5
3 C 99 1
4 D 95 2
Record of student 2
2 B 89 5

Text file Binary file


It is a sequence of bits or It is a customised format
bytes or characters which depending upon the users
in form of lines, paragraphs need
Student file
Rollno name address phno
Staff file
Staffcode name designation
Less prone to get corrupt as Can easily get corrupted,
changes reflects as soon as single bit change can affect
made and can be undone the whole data
Store only plain text in a file Stores in binary format
A→ 65→ 1000001 then saved
Can store audio, text, images
in a single file.
Widely used and can be Developed and processed in
opened and process in the same programming
many platform or software language
Mostly extension Extension is defined by the
.txt, ,rtf programming language
.dat (data file)

Python works on a file


x=20
print(type(x))
Output
<class ‘int’>
Meaning of the line????
x is an object of class int
Python Object Oriented Language
→ class - layout or blueprint or circuit diagram of physics
practical or step to solve an equation in Mathematics or step
for salt analysis in Chemistry or plan of your house
● Components or data
● Behaviour or method or function
● Class is combination of component + behaviour
● Called Encapsulation
● Planning or paper work or imaginary
→ object - instance of class, occupy space, changes can be
done
● Component +behaviour that occupies space in RAM
● Variable → called object
● Because it has components and functions
● Data is called data member or data member of a
class
● Function is called member function or function of a
class
● Call or invoke we use dot(.) operator
● s.upper() → s is the name of the object and upper()
of the member function
Example
Animal class
Car class
American Spitz Dog object (dog is an instance of class
Dogl)
Maruti class
Maruti Ciaz Object

Object in computer is a variable which occupies memory


x=20
Class int
Object x
Data 20

When a variable is declared in Python it is called an


OBJECT

How to create the File object? Characteristics of the file


object?
File object is
● It is also known as File handler
● Name in RAM to refer file on the disk is called file object
● File object has a mode which type of the file object, can
create a file object to read (ONLY), write(ONLY),
append(ONLY), rewrite(Read as well write)
● Once file object is created and mode is assigned then
mode cannot be changed
● File can be opened again
● Good programming practice says open file just once and
to reopen close the file, avoid multiple opening of the
same file at any point of time
File object is create open() →
1. creates file object
2. Relationship or Connected file on the disk
3. Mode of the file
Syntax
Open function takes 2 parameter
1. Name of the file on the disk can be string or string
variable
2. Mode in which you are opening the file (what you want to
do in the file?????)
Modes of the file:

mode description
r Read or input
When you want to read a file, get data from the
file
w Write or output
When you want to write in file, put data in the
file
r+ Read as well write
When you want to overwrite
NO new data will be added
Size of file will remains the same
w+ Write then read
Creates the file, erase the previous data write
new data then read
a Append
Add at the end
a+ Append and read
Previous data can be read, new will be added,
no overwriting

For binary data file write b after the mode eg r→ rb


Eg
F=open(“a.txt”,”r”)
→ meaning
File object or File handler F
Name of file on disk is “a.txt”
Mode of the File object r or read

F1=open(“abc.txt”,”r+”)
File object F1
Name of file on disk is “abc.txt”
Mode of the File object r+ or rewrite

File=open(“story.txt”,”w”)
File object File
File name “story.txt”
Mode of file object w or write

Remember:
Mode is for File Object not FILE
When I say file object is a read object, what does this mean?
Ans
We can give the command to read through this file object
ONLY

Explain the meaning of “the file object is a+ or


F=open(“a.txt”,”a+”) ”
Ans
Using File object F, we can give commands to append in the
file or read the previous data from the file.
Referencing a File - referring the file along with its location
Path of the file: - location+file name

1. Absolute referencing
- Start from the drive
- Then root
- Then folder
- Then the file name
Program1.py absolute path
C:\\flutter\\bin\\b1\\program1.py
print("c:\futter\bin\bin1\program1.py")
c:utterinin1\program1.py
>>> print("c:\\futter\\bin\\bin1\\program1.py")
c:\futter\bin\bin1\program1.py
>>> print(r"c:\futter\bin\bin1\program1.py")
c:\futter\bin\bin1\program1.py
Raw string - without formatting
Use r in print
print(r” “)
Example
>>> print("hello\nfriends")
hello
friends
>>> print(r"hello\nfriends")
hello\nfriends

Format string
- Use f
print(f”the name is {name} and address is {address}”)
- Use format
>>> print("value of a is {1} and value of b is
{0}".format(a,b))
value of a is 900 and value of b is 90

- Use %
>>> a=90
>>> b=900
>>> print("value of a is %s and value of b is %s"%(a,b))
value of a is 90 and value of b is 900
>>> print("value of a is %s and value of b is %s"%(b,a))
value of a is 900 and value of b is 90
Let’s assume there is a file project.py under examples folder
C:\\Python\\examples\\project.py
2. Relative referencing
- CWD or current working folder
- Start the folder below the Current working folder
Let’s program2.py and CWD is flutter
bin\\b1\\program2.py
..bin\\b1\\program2.py

Lets CWD is Python and I want open a file “a.txt” in the lib
folder
Absolute path Relative path
c:\\python\\lib\\a.txt lib\\a.txt
Let’s CWD Python you want open a file “story.txt” in bin of
flutter folder
Absolute path Relative path
c:\\flutter\\bin\\story.txt As bin in not under my CWD
so relative path is not
possible
Let’s CWD B1 and want to open a file “one.txt” in B2 folder
Absolute path Relative path
c:\\flutter\\bin\\b2\\one.txt Not possible because B2 is
not used B1
Let’s CWD is B1 and want to open a file “a1.txt” in bin folder
Absolute path Relative path
c:\\flutter\\bin\\a1.txt Not possible , bin folder is
above B1( bin is parent of
B1)

In Python when you write in “ “ with \, consider


as escape sequence character, for giving path
instead of \ you will \\. \ tells Python consider the
second \ and don’t consider as escape sequence
character
Q
To open a file “story.txt” in pulkit_12-a folder
under Python39 folder and your cwd is Python39
Ans
Absolute path
F2=open("c:\\Python39\\pulkit_12-a\\story.txt","r"
)
Relative path
F3=open("pulkit_12-a\\story.txt","r")

QWhat will happen if you write


F3=open(“\\pulkit_12-a\\story.txt”,”r”)
Ans
When we begin with \\ it means ROOT folder (\), this
statement means root folder has pulkit_12-a, that folder
has story.txt file
Q When we need to give path?
Ans
Path is required if the file is not present in the CWD

Closing the file close()


fileobject.close()
Why closing is important ?
Ans
1. It is good programming habit
2. OS saves the changes in RAM to disk
3. When we opt for the auto saving option of the OS, there
are chances of data loss.
4. Some OS restrict opening of file till you close the
previously opened file in the same program
5. Some OS opens a file and locks so if you want to open
again you must close it
Text File
Write in file “w” or “a”
If open file in “w” mode removes previous data overwrites
new data, if no file then creates
If open file in “a” mode add after last byte, previous data is
not removed
If open “w+” mode can read after writing
If open “a+” mode read previous data and new data will
ben added at end
1. write()
2. writelines()

write()
File handler.write(string)

- One write() writes one character, one word, one line


- Loop is used to add more lines, words, characters
Q Write a program in Python to accept 5 names of students
and add in a file “student.txt”
File=open("student.txt","w")
x=int(input("Enter number of students:"))
for i in range(x):
n=input("Enter the name :")
File.write(n)
File.close()

File=open("student.txt","w")
x=int(input("Enter number of students:"))
for i in range(x):
n=input("Enter the name :")
File.write(n+"\n")
File.close()

File.write(n)
File.write(“\n”)

Q Write a program in Python to accept Rollno, name and


marks of n students and write a file “marks.txt”
Rollno Name Marks
File=open("student.txt","w")
x=int(input("Enter number of students:"))
#print heading in the file
rec="Rollno\tName\t\tMarks\n"
File.write(rec)
for i in range(x):
r=int(input("Enter Rollno:"))
n=input("Enter the name :")
m=float(input("Enter Marks"))
rec=str(r)+"\t"+n+"\t\t"+str(m)+"\n"
File.write(rec)
File.close()

File=open("student.txt","w")
x=int(input("Enter number of students:"))
rec="Rollno\tName\t\tMarks\n"
File.write(rec)
for i in range(x):
r=int(input("Enter Rollno:"))
File.write(str(r)+"\t")
n=input("Enter the name :")
File.write(n+"\t\t")
m=float(input("Enter Marks"))
File.write(str(m)+"\n")
File.close()

Writelines()
File=open("student.txt","w")
x=int(input("Enter number of students:"))
l=[]
for i in range(x):
n=input("Enter the name :")
l.append(n+"\n") #\n just for new line
File.writelines(l) #outside the loop
File.close()
File=open("student.txt","w") # “a” for append
x=int(input("Enter number of students:"))
rec="Rollno\tName\t\tMarks\n"
l=[]
l.append(rec)
for i in range(x):
r=int(input("Enter Rollno:"))
n=input("Enter the name :")
m=float(input("Enter Marks"))
rec=str(r)+"\t"+n+"\t"+str(m)+"\n"
l.append(rec)
File.writelines(l) #will write each string in the list as a line
File.close()
Writelines cannot print “\n” on its own
“\n” should be there in string

Reading a text File


- Create a file object or file handler
- Open the file in “read” mode
- Creates a File pointer
- Mark beginning BOF mark , Mark at end EOF,
non-graphical character(not printable on screen eg
escape sequence \n )
- Each character occupies 1 byte of number
A12%34.6
8 bytes of data
- Each data is converted into ASCII → Binary → saved
1. read() → reads the whole file and store in a form of a
string, read(n) where n is number of bytes. Read till
EOF ONLY, if n is more than number of characters in the
file Python will not give any error.
A=File.read(5)
It will read first 5 bytes from the file
Q if my file contains
ABCDEFGHIJK
I open my file in “r” mode
A=File.read(5)
Where is my file pointer?
Ans
Read ABCDE
So the file pointer is at F

Q if my file contains
ABCDEFGHIJK
I open my file in “r” mode
A=File.read(5) # ABCDE
B=File.read(4) #FGHI
C=File.read(3) #jk\n
print(A)
print(B)
print(C)
Is this program correct, if yes, what will be the output?

Q if my file contains
ABCDEFGHIJK
I open my file in “r” mode
File=open(“a.txt”,”r”)
A=File.read(5)

Open() closes the previous opened file


File pointer was 15the bytes, reopen file pointer will shift
to first byte
File is in RAM till the File object or File handler is in the
memory, when the handler is released then file closes
automatically

REMEMBER: every open statement places the file


pointer on the 1st byte.
2. readline() - reads line wise, readline(n) n bytes in each
line
Eg
File.readline(10) → reads first 10 bytes
Reads one line at a time
- Loop is used read line wise using function readline()
str=’’
while str:
str=File.readline()
print(str)

while True:
str=File.readline()
if str==’’: #no space in between quotes
Break
print(str)
\n after the line in the file and \n in print()
print(str,end=””) # reduce one \n
3. readlines() → returns all the lines in the form of list of
strings
File=open("a11.txt","r")
s=File.readlines()
for x in s:
print(x)
File.close()

File=open("a11.txt","r")
S=File.readlines()
for x in S:
print(x)
Method of reading character by character

read() readline() readlines()


S=File.read() while True: S=File.readlines()
for a in S: S=File.readline() for a in S:
if S=="": #each line
Data is processed break for x in a:
character, S is for x in S: #each character
<class 'str'> print(x)
Here S is a string
of line, need Loop
for each character

def character_wise1(): def character_wise2(): def character_wise3():


File=open("a11.txt","r")
File=open("a11.txt","r") File=open("a11.txt","r") data=File.readlines()
data=File.read() while True: #data is <class 'list'>, list
#data is <class 'str'> S=File.readline() of strings
for c in data: #read line by line for a in data:#one
print(c, end=" ") if S=="": string or one line
File.close() break for s in a:#each
for a in S: character in a line
#character of each line print(s,end=" ")
print(a,end=" ") File.close()
File.close()
Method to read word by word

read() readline() readlines()


S=File.read().split(“ while True: S=File.readlines()
“) S=File.readline() for a in S:
for a in S: if S=="": #each line
Break d=a.split()
Data is processed d=S.split() for x in d:
character, S is for x in d: #each character
<class 'str'> print(x)
Here S is a string Here S of list of
of line,split into list string, a is one
of words, need line, split a into list
Loop for each word of words, loop for
each word
def word_wise1(): def word_wise2(): def read_line():
File=open("a11.txt","r")
File=open("a11.txt","r") File=open("a11.txt","r") while True:
while True: S=File.readline()
data=File.read().split() S=File.readline() if S=="": #read EOF
#data is <class 'list'>, #read line by line mark then S store None
list of words if S=="": break
#d=File.read() break print(S)
#data=d.split() d=S.split()#line is File.close()
for c in data: split in <class 'list'> of
print(c,end=", ") words
File.close() for a in d:
#character of each line
print(a,end=", ")
File.close()
Method to read line by line

read() readline() readlines()


S=File.read().split(“ while True: S=File.readlines()
\n “) S=File.readline() for a in S:
for a in S: if S=="": print(a)
Break
Data is processed print(S) Here S of list of
character, S is Here S is a string string, a is one line
<class 'str'> of line,loop for all
the lines
def read_line1(): def read_line2(): def read_line3():

File=open("a11.txt","r") File=open("a11.txt","r") File=open("a11.txt","r")


while True:
data=File.read().split("\ S=File.readline() # S=File.readlines()#list
n") #read all the lines readling one line at a of lines
and then split time for a in S: #loop for
for a in data: if S=="": #read each line
print(a) EOF mark then S store print(a)
File.close() None File.close()
break
print(S)
File.close()

Question
Q1 Write a program in Python to display number upper
and lower characters from the file “abc.txt”
Solution
- Open the file read mode
- Read using read(), readline(),readlines() to process
character by character
- For counting declare a variable outside the loop initialize
with 0 before starting the loop
- Loop
- Check and increment
- Print the value of count outside the loop after processing
def count_upper_lowercase():
File=open("a11.txt","r")
data=File.read() # split into character
count_u=0
count_l=0
for a in data:
if a in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
#a.isupper()
count_u+=1
elif a.islower(): #"a"<=a<="z"
count_l+=1
print("Number of upper case ",count_u)
print("Number of lower case ",count_l)
File.close()

Q2 Write a program in Python to count and display number of


words in a text file “story.txt”
Ans

def count_words1():
File=open("a11.txt","r")
data=File.read() # split into character
count_s=0
for a in data:
if a==" " or a=="\n":
count_s+=1
print("Number of words ",count_s)
File.close()

def count_words2():
File=open("a11.txt","r")
data=File.read().split() # split into character
l=len(data)
print("number of words ",l)
File.close()

Q Write a program in Python to accept a filename from the


user and display all the words starting with a vowel
Ans
fname=input(“enter the file name”)
If “.txt” in fname:
pass
else:
fname=fname+”.txt” #optional user is only inputting name
File=open(fname,”r”)
T=File.readlines()
for x in T:
d=x.split()
for y in d:
if y[0] in “AEIOUaeiou”:
print(y, end=” “)
print()

Q Write a program in Python to display all the words that ends with a
vowels
Ans
S=File.readlines()
for a in S:
for x in a:
if x[-1] in 'AEIOUaeiou':
print(x)

Q Write a program in Python to count all the lines which


begins with ‘The’.
Ans
File =open(“story.txt”,”r”)
count=0
while True:
s=File.readline()
if s==””:
break
if s[0] in ‘Tt’ and s[1] in ‘Hh” and s[2] in ‘Ee’ and s[3]==’
‘:
count+=1
Print(‘number of lines”,count)
f=open("student.txt","r")
c=0
l=f.readlines() #list of strings
for i in l: # has one line
d=i.split()
if d[0]==’The’ or d[0] ==’the’:
if i[0] in ‘Tt’ and i[1] in ‘Hh’ and i[2] in ‘Ee’ and i[3]==’ ‘:
c+=1
if i[0]==’ ‘ and i[1] in ‘Tt’ and i[2] in ‘Hh’ and i[3] in ‘Ee’ and i[4]==’ ‘:
c+=1

print("number of lines",c)

If d[0]!=’The’ and d[0] !=’the’:

With in Python
With statement → program code will be easier and compact
with statement as Filehandlername:
statement(s)
No need to give close
With closes automatically
with open(“a11.txt”,”r”) as F:
while True:
s=F.readline()
if s==””:
Break
print(s)
Single line opening and closing the file
with open(“ax.txt”,”w”) as File:
for a in range(10):
s=input(“enter the line”)
File.writeline(s+”\n”)
NOTE: if mode is not specified at the time of opening
the file it will open in read “r” mode.
File=open(“a.txt”)
This means the file is opened in read mode

Opening a file in read mode and check


1. Exception handling
2. Using os library

Standard library os in Python


- Do task on OS (operating system)
- Create or change folder
import os
1. getcwd() → current working the folder/ directory
import os
print(os.getcwd())
2. mkdir() → make a directory or folder, give name of the folder
using absolute path or relative path
import os
os.mkdir(“c:\\newdir”)
3. chdir() → change working directory or folder, take the control
in the folder
os.chdir(“e:\\newdir”)
Name of the folder in “ “
4. rmdir() → remove the directory
a. Remove only when it empty
b. Folder has sub folder then remove them first
c. Absolute or relative path can be given
d. Should not your cwd
os.rmdir(“e:\\newdir”)
Name of the folder to remove
5. listdir() → displays files and folders
#write a program to count number of .py files in your folder
import os
os.chdir("c:\\python39")
d=os.listdir()
count=0
for a in d:
if ".py" in a:
count+=1
print("number of .py files are", count)
#write a program to accept a file name from user and check
file exist in the folder
import os
os.chdir("c:\\python39")
fname=input("enter filename:")
d=os.listdir()
if fname in d:
print("file exist")
else:
print("file does not exist")

6. close() → to close a file


file.close()
Or
os.close(“a11.txt”)

7. remove() → to remove a file


os.remove(“e:\\a.txt”)
Name of the file
import os
fname=input(“enter the name of the file:”)
if os.path.isfile(fname):
os.remove(fname)
print(“File removed successfully”)
else:
print(“no such file”)
try:
os.remove(fname)
print(“file removed successfully”)
except FileNotFoundError:
print(“No such File”)
8. Rename → change name of the file
os.rename(“old name”,”new name”)
Path to be given in old name
9. os.path.exists(path)
10. os.path.isfile()
11. os.path.isdir()
#write a program to accept a file name from the user and
check if file or folder
import os
os.chdir("c:\\python39")
fname=input("enter the name")
if os.path.isfile(fname):
print("its a file")
elif os.path.isdir(fname):
print("it's a folder")
else:
print("no such file or folder")

#write a program to accept a file name from the user and


check if file or folder
import os
os.chdir("c:\\python39")
fname=input("enter the name")
if os.path.isfile(fname):
print("its a file")
f=os.open(fname,os.O_RDONLY)
d=os.read(f,40)
print(d)
elif os.path.isdir(fname):
print("it's a folder")
else:
print("no such file or folder")

os.write() → writing in the file


Sample Questions
Fill in the blanks
1. A collection of bytes stored in computer’s secondary
memory is known as File _______.
2. _File Handling__________ is a process of storing data into
files and allows to performs various tasks such as read,
write, append, search and modify in files.
3. The transfer of data from program to memory (RAM) to
permanent storage device (hard disk) and vice versa are
known as __Input-output operation______.
In file handling when you read a file → input
Write in file → output
4. A ____text__ is a file that stores data in a specific format on
secondary storage devices.
5. In ________text___ files each line terminates with EOL or ‘\n’
or carriage return, or ‘\r\n’.
6. To open file data.txt for reading, open function will be written
as f = ___open(“data.txt”,”r”)____.
Can be written without “r”
7. To open file data.txt for writing, open function will be written
as f = _____open(“data.txt”,”w”)___.
“w” is compulsory
8. In f=open(“data.txt”,”w”), f refers to file object or file handler
________.
9. To close file in a program close() _______ function is used.
closed → check if file is still open or not
if File.closed: # data
print(“file is closed”)
else:
print(“file is still open”)
10. A ____F.read(15)_ function reads first 15 characters of file.
D=F.read(5)
D=F.read() # will read 5th byte onwards
D=F.read(10) # will read 6th onwards 10 characters
11. A read()_________ function reads most n bytes and returns
the read bytes in the form of a string.
12. A __readlines()_______ function reads all lines from the file.
13. A ___pickle.dump()____ function requires a string
(File_Path) as parameter to write in the file.
14. A _____ function requires a sequence of lines, lists, tuples
etc. to write data into file.
15. To add data into an existing file __”a”______ mode is used.
16. A __write()_____ function is used to write contents of
buffer onto storage.
17. A text file stores data in ___character__ or _lines___ form.
18. A _____binary______ is plain text file which contains list of
data in tabular form.
19. You can create a file using ___open()_____ function in
python.
20. A _____r+_____ symbol is used to perform reading as well
as writing on files in python.
https://www.tutorialaicsip.com/cs-xii-qna/file-handling-in-python-
class-12/
https://www.pathwalla.com/2020/10/
http://python.mykvs.in/presentation.php
Exception Handling
- Runtime error is called exception
- Handling this error is called exception Handling
- In most languages
- Try :- give statement in try block where we may get error
- Jump on except if there is error
- If no error runs all statements

-
- What is the advantage of exception handling?
Ans:
1. Eliminates runtime error
2. Behaves like a normal program

Exceptions in Python
1. ZeroDivisionError - when you divide a number by 0
ZeroDivisionError: division by zero
2. ValueError- when the conversion is not possible
ValueError: invalid literal for int() with base 10: 'a12'

3. TypeError - when datatype is not acceptable


L=[1,2,3]
print(L[“1”])
As index of a list is a number
TypeError: list indices must be integers or slices, not float
4. IndexError- When the error is because of Index

5. KeyError- the key referred by the dictionary is missing


KeyError: '3'
6. NameError- referring to a variable which doesnot exist or
the out of the scope
NameError: name 'y' is not defined
7. IOError - When you does not write/ read rights
8. PermissionError- try to write in a readonly file
9. FileNotFoundError - try to open a file in read mode and
the file does not exist
FileNotFoundError: [Errno 2] No such file or directory:
'a11'
10. EOFError - when you try to read the file after EOF
11. ImportError or ModuleNotFoundError - if the module or
import is not present
try:
a=eval(input("Enter the first number:"))
b=eval(input("Enter the second number:"))

c=a//b
print(c)
except ZeroDivisionError:
print("error in input")
except ValueError:
print("cannot divide by this")
except FloatingPointError:
print("floating point")
except TypeError:

print("cannot do division by this type")

try:
Fname=input("enter the filename:")
F=open(Fname,"r")
print("file opened")
except FileNotFoundError:
print("please check")

finally: block finally is executed if or not a runtime error


You can give such statements without finally as well
With statement
- No need to give
- Creates a file handler or file object
- Simplifies the code

with open("a11.txt","r") as File:


while True:
Data=File.readline()
if Data=="":
break
print(Data)
print("file status:",File.closed)
Binary write
#rollno,name,age
import pickle
F=open("Student1.dat","wb")
rep='y'

while rep in "Yy":


D={}
rollno=int(input("Enter Rollno:"))
name=input("enter name:")
age=int(input("Ener age:"))
marks=float(input("Enter marks:"))
D[rollno]=[name,age,marks]
pickle.dump(D,F)
rep=input("Want to add more records:")
F.close()

Binary file read


import pickle
Use load() to read
Eg
L=pickle.load(File)

Method 1:
Try -- except to read a binary file
#WAP to accept name and find if the student is in the class or not

def findall():
File=open("student.dat","rb")
L=[]
count=0
name=input("Enter name to search:")
try:
while True:
L=pickle.load(File)

if L[1]==name: #name in L[1]:


print("found:",L[0],L[1],L[2])
count+=1 #count will change if and only of the name
exists
except EOFError:
File.close()
if count==0:
print("No such student")
#findall()

def findall1():
File=open("student.dat","rb")
L=[]
count=0
name=input("Enter name to search:")
try:
while True:
L=pickle.load(File)

if L[1]==name: #name in L[1]:


print("found:",L[0],L[1],L[2])
break #loop will terminate if the name exist
except EOFError:
print("No such student")
File.close()

findall1()

with open(“student.dat”,”rb”) as File:


try:
while True:
L=pickle.load(File)
print(L)
Except EOFError:
print(“over”)

Delete data from the binary file


- Open source in read mode
- Open temporary file in write mode
- Accept on basis of which we want to accept the data
- Source read → write temporary all those which we want to
retain (except the record to remove we will write all the
record”)
- Close both the file
- Remove source file
- Rename temporary file as source file

#rollno,name,age
import pickle
import os
L=[]
F1=open("Student.dat","rb")
F2=open("Temp.dat","wb")
roll=int(input("Enter roll no for deletion:"))
try:
while True:
L=pickle.load(F1)
if L[0]!=roll: # execpt this rollno write in the temperorary file
pickle.dump(L,F2)
except EOFError:
F1.close()
F2.close()
os.remove("Student.dat")
os.rename("Temp.dat","Student.dat")
Modify File
1. Using Temporary file
2. Without using temporary file
Using Temporary file
Algorithm
Step 1: open source file read mode
Step 2: open a temporary file in write mode
Step 3: Accept data for modification
Step 4: read the file
Step 5: if data match with data to modify: write modified value
Else: write the original data in temporary file
If you are writing algorithm of delete:
If data matches with data to delete: pass else: write in the
temporary file or If data does not matches with data to delete:
write in the temporary file
Step 6: repeat the process till end of file
Step 7: close both the files
Step 8: remove original file
Step 9: rename temporary file as original file
Step 10: stop
Selected records to be modified:
def Modify():
F1=open("student.dat","rb")
F2=open("temp.dat","wb")
R=int(input("Enter Rollno to modify"))
N=input("Enter new name:")
M=float(input("Enter the modified marks"))
L=[]
try:
while True:
L=pickle.load(F1)
if L[0]==R:
L[1]=N
L[2]=M
pickle.dump(L,F2)
else:
pickle.dump(L,F2)
except EOFError:
F1.close()
F2.close()
os.remove("student.dat")
os.rename("temp.dat","student.dat")

All the records to be modified


import pickle
import os
def Modify():
F1=open("student.dat","rb")
F2=open("temp.dat","wb")

L=[]
try:
while True:
L=pickle.load(F1)
print("Rollno=",L[0],"\tName=",L[1])
M=float(input("Enter the modified marks"))
L[2]=M
pickle.dump(L,F2)
except EOFError:
F1.close()
F2.close()
os.remove("student.dat")
os.rename("temp.dat","student.dat")

Python manages the file pointer and this file pointer can
processed in Python program
To process the File pointer
1. seek() → places the file pointer
2. tell() → tells the position of file pointer
tell()
- No parameter
- Fileobject.tell()
- File pointer starts from 0
- When you open a file in “r”, “w” mode file pointer is on 0th
byte, in “a” then it is at the end after the last byte
-

>>> F=open("a11.txt","r")
>>> D=F.read(10)
>>> print(D)
Pineapple
>>> print(F.tell())
10
>>> D=F.read(5)
>>> print(F.tell())
15
>>> F=open("abcd.txt","w")
>>> F.write("ABCDE")
5
>>> print(F.tell())
5
>>> F.close()
>>> F=open("abcd.txt","a") #places the pointer after the last byte
>>> print(F.tell())
5
>>> F.write("HIJ")
3
>>> print(F.tell())
8
>>> F=open("abcd.txt","w") #places the pointer on 0 byte
>>> print(F.tell())
0
>>> F.write("HIJ")
3
>>> print(F.tell())
3

seek ()
- Places the file pointer
- File opened r, r+,w+ any mode
Syntax
Example
File.seek(10) Place on the pointer on 10(11th ) byte
File.seek(10,0) same
File.seek(-5,1) left by 5 bytes from current position
File.seek(5,1) right by 5 bytes from current position
File.seek(-5,2) right by 5 byte from last byte
file.seek(0,2) places the pointer on the last byte

Remember:
1. From BOF(0th byte) you cannot go back (can’t go towards
left) → negative values is not allowed
File.seek(-5,0)
Is WRONG
2. From EOF(last byte) you cannot go further( can’t go towards
right) → positive values is not allowed
File.seek(5,2)
Is WRONG
3. But from current go back or further → negative and positive
both are allowed depending upon the direction
File.seek(1,1)
File.seek(-1,1)
Both are CORRECT
Eg
WAP to read last 10 byte of “abc.txt”)
File=open(“abc.txt”,”r”)
File.seek(-10,2)
D=File.read()
print(D)

WAP to change all the occurrences of “A” with “a”


File=open("abc.txt","r+")
while True:
t=File.tell()#trap the position before reading
r=File.read(1)
print(r,end=" ")
if r=="":
break
if r=="a":
r='A'
File.seek(t) #place the file pointer on the position
print(File.tell())
File.write(r)

File.close()
How Python read
def Modify():
File=open("student.dat","rb+")
L=[]
rollno=int(input("Enter rollno to modify"))
try:
while True:
t=File.tell() #track position before load
L=pickle.load(File)
if rollno==L[0]:
print("Name:",L[1],"\t previous marks=",L[2])
m=float(input("Enter new marks"))
File.seek(t)# seek the position before dump
L[2]=m
pickle.dump(L,File)
break
except EOFError:
print("No such Rollno")
File.close()

Python can give unpickling runtime error:


Data type change to float (any integer value is multiplied by 0.25
answer is in float) → in such situation we will not overwrite but we
will use the technique of temporary file
1. pickle.PicklingError - trying to write unpicklable data
2. pickle.UnPicklingError - when data is corrupted, data type is
changes, data format is change, size changes, file has no
write access

When we try to seek a byte which is not reachable, it gives runtime


error
If you give :
File=open("abc.txt","r+")
while True:
t=File.tell()#trap the position before reading
r=File.read(1)
print(r,end=" ")
if r=="":
break
if r=="a":
r='A'
File.write(r)
File.close()
Then it will write at the end terminates
Other type of Files
1. CSV - Comma separated File
2. TSV- Tab Separated File
3. PSV - Pipe(|) Separated File

CSV File
- Data is separated by a comma(,)
- Used to store huge amounts of data
- By default the separator is comma, default delimiter
- You can the separator
- To process a csv file read in text → split to break into
different field
- Easier method of using csv module
- import csv

File open
open() function is used to open a CSV file
F=open(“s.csv”,”w”)
Remember
You will not write b as it is not a binary file

File close
Using close() function

Write in the file


1. File handler or file object using open() function
File object=open(filename,”w”)
Or
“a” if you want to add
Example
File=open(“s.csv”,”w”)
You can give newline character of the file
By default newline character of a csv file are
Macintosh \r Carriage or return
Unix \n newline character
DOS or Windows \r or \n
Other OS \0 (NULL)
File=open(“s.csv”,”w”,newline=”\n”)
File=open(“s.csv”,”w”,newline=”;”)

2. Declare a writer object


2 parameter:
- File object
- Delimiter , where delimiter is optional
writer() of csv class
Cwriter=csv.writer(File object)
Cwriter=csv.writer(Fileobject,delimiter=”,”)
Cwriter=csv.write(Fileobject,delimiter=”#”)
3. To write
a. writerow() - single list or tuple
b. writerows() - nested list or nested tuple

#create a employee file emp_no, name, job, salary


import csv
def create():
File=open("emp.csv","w",newline="\n")
rep='y'
cwriter=csv.writer(File,delimiter=",")
cwriter.writerow(["Empno","Name","Job","Salary"]) #header of the
csv file
while rep in "Yy":
empno=int(input("Enter employee number:"))
name=input("Enter name:")
job=input("Enter Job:")
salary=float(input("Enter salary:"))
L=[empno,name,job,salary]
cwriter.writerow(L)
rep=input("Want to add more:")
File.close()

#using writerows()

def create2():
File=open("emp.csv","w",newline="\n")
rep='y'
cwriter=csv.writer(File,delimiter=",")
cwriter.writerow(["Empno","Name","Job","Salary"]) #header of the
csv file
L=[]
while rep in "Yy":
empno=int(input("Enter employee number:"))
name=input("Enter name:")
job=input("Enter Job:")
salary=float(input("Enter salary:"))
L.append([empno,name,job,salary])
rep=input("Want to add more:")
cwriter.writerows(L)
File.close()

#to append in csv file

def append():
File=open("emp.csv","a",newline="\n")
rep='y'
cwriter=csv.writer(File,delimiter=",")
# no need to give head as the header is already there
while rep in "Yy":
empno=int(input("Enter employee number:"))
name=input("Enter name:")
job=input("Enter Job:")
salary=float(input("Enter salary:"))
L=[empno,name,job,salary]
cwriter.writerow(L)
rep=input("Want to add more:")
File.close()
append()

Reading a csv file


1. Declare a file object using open() function
File=open(file,”r”)
File=open(“s.csv”,”r”)
File=open(“S.csv”,”r”,newline=”\n”)
2. Declare a reader object
readerobject=csv.reader(fileobject)
readerobject=csv.reader(fileobject,delimiter=”,”)
Example
creader=csv.reader(File,delimiter=”,”)
Name given by the programmer
If you don’t give newline [] element will be stored in the file
[[101,”A”,”A”,2000],[],[102,”B”,”B”,3000],[]]
Why we use newline while opening a csv file?
So that system is not creating or storing an empty row

Csv gets data in text format so use int() or float() to convert


numeric or calculation

import csv
def readall1():
File=open("emp.csv","r",newline="\n")
rep='y'
creader=csv.reader(File,delimiter=",")
count=0
for d in creader:
print(d)
File.close()

def readall2():
File=open("emp.csv","r",newline="\n")
rep='y'
creader=csv.reader(File,delimiter=",")
for d in creader:
print("{0:10}{1:20}{2:20}{3:10}".format(d[0],d[1],d[2],d[3]))
File.close()

def readall3():
File=open("emp.csv","r",newline="\n")
rep='y'
creader=csv.reader(File,delimiter=",")
count=0
for d in creader:
if count==0:
print("{0:10}{1:20}{2:20}{3:10}".format(d[0],d[1],d[2],d[3]))
elif float(d[3])>2500:
print("{0:10}{1:20}{2:20}{3:10}".format(d[0],d[1],d[2],d[3]))
count+=1

File.close()
def readall4():
File=open("emp.csv","r",newline="\n")
rep='y'
creader=csv.reader(File,delimiter=",")
count=0
for d in creader:
if count==0:
print("{0:10}{1:20}{2:20}{3:10}".format(d[0],d[1],d[2],d[3]))
elif d[2]=='A':
print("{0:10}{1:20}{2:20}{3:10}".format(d[0],d[1],d[2],d[3]))
count+=1

File.close()
readall4()
Calculate and display the annual salary
def readall3():
File=open("emp.csv","r",newline="\n")
rep='y'
creader=csv.reader(File,delimiter=",")
count=0
for d in creader:
if count==0:

print("{0:10}{1:20}{2:20}{3:10}{4:20}".format(d[0],d[1],d[2],d[3],"Ann
ual Salary"))
elif float(d[3])>2500:

print("{0:10}{1:20}{2:20}{3:10}{4:10}".format(d[0],d[1],d[2],d[3],float
(d[3])*12))
count+=1

File.close()

You might also like