0% found this document useful (0 votes)
27 views

File Handling Full Notes

File handling allows storing data permanently in files. There are different file types like text, binary, and CSV. The document discusses opening, reading, and writing to files in Python. It covers opening files using open() and with, absolute vs relative paths, different modes for reading and writing, and functions for text, binary, and CSV files like read(), write(), readline(), and CSV reader/writer. Sample programs demonstrate reading, writing, searching, updating records in binary and CSV files.

Uploaded by

pantheanandal23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

File Handling Full Notes

File handling allows storing data permanently in files. There are different file types like text, binary, and CSV. The document discusses opening, reading, and writing to files in Python. It covers opening files using open() and with, absolute vs relative paths, different modes for reading and writing, and functions for text, binary, and CSV files like read(), write(), readline(), and CSV reader/writer. Sample programs demonstrate reading, writing, searching, updating records in binary and CSV files.

Uploaded by

pantheanandal23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

File Handling

• It is a method of storing data permanently in files.


• It is also known as Data file handling.
• We can store data in Text, Binary or CSV files.

Advantages
✔ Data is stored permanently.
✔ Already existing data can be used.
✔ Large amount of data can be processed easily.
✔ Data can be stored in different files and methods.

File opening methods


using open() function
file_object/variable = “filename/address”, “mode”)
Example
a=open(“hello.txt/bin/dat/csv”, “w”)
If we open with open() it is mandatory to close file
using file_object.close()

using with keyword


with open (“filename/address”, “mode”) as
file_object:
Example
with open(“hello.txt/bin/dat/csv”, “w”) as a:
Note:- using with keyword, there is no need to close
file.

Absolute and Relative path


Absolute Path – Complete address or path.
D:\new\new1\today.txt
Relative path – Current path address.
today.txt
Note:- We can create raw string to avoid special
meaning of escape sequence.
r“D:\new\new1\today.txt”
Modes in File Handling
Modes Tex Binar CS
t y V
Reading data from files (default r rb r
mode).
Writing in files, creates a new file w wb w
(If not exist), deletes the existing
data.
Appending, adding data to end a ab a
of existing file, creates a new file
(If not exist).
Note:
we can add ( + ) to modes for performing both actions
(i.e, reading and writing)
r+ → read and write
w+ → write and read
a+ →append and read

Text file (Extension is .txt)


• Data is stored in ASCII or Unicode (Strings).
• Data is in Human Readable form.
• Execution is slow.

Binary file (Extension is .bin .dat)


• Data is stored in machine/binary form in memory
location (as in memory).
• These files are not in human readable form.
• Execution is faster.

Comma Separated Values (CSV) (Extension .csv)


• Data is stored in ASCII or Unicode in Tabular
form.
• Large amount of data can be easily stored and
managed.
• Tabular data can be easily imported or exported to
databases.
• Data can be manipulated through list.

Text file
Reading from text file
Sample file “today.txt”
Hello world!
We are learning File handling.

read()
Reads data from text file in read mode.
Stores data in string form.
Example
p=open(“today.txt”, “r”)
k=p.read()
print(k)
p.close()
Output:-
Hello world!
We are learning File handling.
Note- We can give integer value for specific character
reading.
p=open(“today.txt”, “r”)
k=p.read(5)
print(k)
p.close()
Output:-
Hello

readline()
It reads line by line (one line at a time)
p=open(“today.txt”, “r”)
k=p.readline()
print(k) → Hello world!
p.close()

readlines()
It reads data in string form (each line) and enclosed
with a list.
p=open(“today.txt”, “r”)
k=p.readlines()
print(k) →[“Hello world!”, “We are learning File handling.”]
p.close()
Questions on Text filename
Sample file - “today.txt”
Hello world!
We are learning File handling.
1. Reading all data from file.
2. Reading first 10 characters from file.
3. Reading all data using for loop.
4. Reading all data using while loop.
5. Counting total number of characters/Bytes in file.
6. Counting total number of vowels.
7. Counting total number of words.
8. Counting total number of lines.
9. Counting total number of 5 letter word.
10. Counting total number of lines starting from a
specific letter.

Writing in Text file


write()
It is used to write in text file in string form.
Writelines()
It is used to write multiple lines in string form using
list.

Example
p=open("today.txt","w")
p.write("Hello world!\n")
k="This is line\n"
p.write(k)
a=["Rahul\n","Diya\n","Suraj"]
p.writelines(a)
p.close()

Appending in existing file


p=open(“today.txt”, “a”)
k= “hello”
p.write(k)
p.close()

tell() and seek() function


These functions are used for random access in text
file.
tell() - It returns current position of file pointer.
Syntax – file_pointer.tell()
seek() - It is used to move file pointer within a text
file.
Syntax – file_pointer.seek(number of characters)
Note:- Pointer starts with 0.

Reading and writing from file


p=open("today.txt","w+")
p.write("Hello world!\n")
k="This is line\n"
p.write(k)
a=["Rahul\n","Diya\n","Suraj"]
print(p.tell())
p.writelines(a)
p.seek(0)
print(p.read())
p.close()
Output
28
Hello world!
This is line
Rahul
Diya
Suraj

Binary Files
What is pickling
Pickling is the process in which data is converted to
byte stream so that it can be stored in binary file.
Pickle module – Module used for binary file.
We will used two function of pickle module.
load() - It is used to read or load data from binary file.
Syntax – pickle.load(file_object)
dump() - It is used to store or dump data into binary
file.
Syntax – pickle.dump(data, file_object)

Example:-
import pickle
p=open("today.dat","wb")
pickle.dump("Hello world",p)
k=["Binary file",4,[5,6]]
pickle.dump(k,p)
p.close()
with open("today.dat","rb") as p:
k=pickle.load(p)
print(k)
k=pickle.load(p)
print(k)
Output
Hello world
['Binary file', 4, [5, 6]]

Complete program [write, append, read, search,


update, copy and delete]
import pickle
def write_binary(): #writing/creating
p=open("today.dat","wb")
k='y'
while k=='y':
r=input("Enter Rollno")
n=input("Enter name")
m=input("Enter Marks")
d=[r,n,m]
pickle.dump(d,p)
k=input("Another record (y/n)")
p.close()
def append_binary(): #appending data
p=open("today.dat","ab")
k='y'
while k=='y':
r=input("Enter Rollno")
n=input("Enter name")
m=input("Enter Marks")
d=[r,n,m]
pickle.dump(d,p)
k=input("Another record (y/n)")
p.close()

def read_binary():
p=open("today.dat","rb")
while True:
try:
k=pickle.load(p)
print(k)
except:
p.close()
print("End of file")
break
def search_binary(): #Searching data
p=open("today.dat","rb")
s=input("Enter searching Rollno")
find=False
while True:
try:
k=pickle.load(p)
if k[0]==s:
print(k)
find=True
p.close()
break
except:
p.close()
print("End of file")
break
if find==False:
print("Data not find")
def update_binary():# Updating data
p=open("today.dat","rb+")
r=input("Enter Rollno")
while True:
try:
location=p.tell()
k=pickle.load(p)
if k[0]==r:
p.seek(location,0)
r=input("Enter Rollno")
n=input("Enter name")
m=input("Enter Marks")
d=[r,n,m]
pickle.dump(d,p)
print("Data Updated")
break
except:
p.close()
break
def copy_binary():
n=input("Enter the file name - ")
p=open("today.dat","rb")
k=open(n+".dat","wb")
while True:
try:
data=pickle.load(p)
pickle.dump(data,k)
except:
print("Records Copied")
p.close()
k.close()
break
def delete_binary():
import os
p=open("today.dat","rb")
k=open("hello.dat","wb")
r=input("Rollno to delete")
while True:
try:
data=pickle.load(p)
if data[0]!=r:
pickle.dump(data,k)
except:
print("Deletion done")
p.close()
k.close()
break
os.remove("today.dat")
os.rename("hello.dat","today.dat")
k=None
while k!=0:
print("0 - Exit")
print("1 - Write")
print("2 - Append")
print("3 - Read")
print("4 - Search")
print("5 - Update")
print("6 - Copy")
print("7 - Delete")
c=int(input("Enter your choice"))
if c==0:
break
elif c==1:
write_binary()
elif c==2:
append_binary()
elif c==3:
read_binary()
elif c==4:
search_binary()
elif c==5:
update_binary()
elif c==6:
copy_binary()
elif c==7:
delete_binary()

Comma Separated Values (CSV file)


csv module
This module is used to read and write in csv file.
Function
csv.reader()
It is used to create csv reader.
csv.writer()
It is used to create csv writer.
We use writerow() and writerows() for reading and
writing.

Complete Program

import csv
def write_csv():
p=open("today.csv","w",newline='') #Newline
will always be Empty
w=csv.writer(p,delimiter="-") #Delimiter
is now - not ,
d=["Rollno","Name","Marks"]
w.writerow(d)
k='y'
while k=='y':
r=input("Enter Rollno")
n=input("Enter name")
m=input("Enter Marks")
d=[r,n,m]
w.writerow(d)
k=input("Another record (y/n)")
p.close()
def read_csv():
p=open("today.csv","r")
d=csv.reader(p)
for x in d:
print(x)
p.close()
def search_csv():
p=open("today.csv","r")
r=csv.reader(p)
roll=input("Enter the Rollno - ")
next(r)
for x in r:
if x[0]==roll:
print(x)
break
else:
print("Not Found")
c=True
while c!=0:
print("0 - Exit")
print("1 - Write")
print("2 - Read")
print("3 - Search")
c=int(input("Enter your choice - "))
if c==0:
break
elif c==1:
write_csv()
elif c==2:
read_csv()
elif c==3:
search_csv()
else:
print("Invalid choice")
continue

You might also like