File Handling in Python – Text, Binary, and CSV Files
Writing in a text file using write() method¶
In [1]:
fobj = open("message.txt", "w")
fobj.write("Hello How are You?")
fobj.write("Hi I am fine")
fobj.write("Thankyou")
fobj.close()
Writing multiple lines in a text file using writelines() method¶
In [3]:
fobj = open("message2.txt", "w")
L = ["Hello How are You?\n", "Hi I am fine\n", "Thankyou\n"]
fobj.writelines(L)
fobj.close()
appending in a text file¶
In [4]:
fobj = open("message2.txt", "a")
L = ["What are you doing\n", "I am taking online class\n"]
fobj.writelines(L)
fobj.close()
In [5]:
fobj = open("message.txt", "a")
fobj.write("\nanjeev singh is a best teacher")
fobj.close()
Reading a text file using read()¶
In [6]:
fobj = open("message.txt", "r") #read mode
string = fobj.read()
print(string)
fobj.close()
Hello How are You?Hi I am fineThankyou anjeev singh is a best teacher
In [7]:
fobj = open("message2.txt", "r") #read mode
string = fobj.read()
print(string)
fobj.close()
Hello How are You? Hi I am fine Thankyou What are you doing I am taking online class
In [8]:
fobj = open("message2.txt", "r") #read mode
string = fobj.read(6)
print(string)
string = fobj.read(4)
print(string)
string = fobj.read(3)
print(string)
fobj.close()
Hello How are
In [9]:
fobj = open("message2.txt", "r") #read mode
string = fobj.read(6)
print(string)
string = fobj.read(4)
print(string)
string = fobj.read(3)
print(string)
string = fobj.read(5)
print(string)
string = fobj.read(3)
print(string)
fobj.close()
Hello How are You? Hi
In [10]:
fobj = open("message2.txt", "r") #read mode
string = fobj.read(6)
print(string)
string = fobj.read(4)
print(string)
string = fobj.read(3)
print(string)
string = fobj.read(5)
print(string)
string = fobj.read(1)
string = fobj.read(2)
print(string)
fobj.close()
Hello How are You? Hi
Reading a text file using readline()¶
In [12]:
fobj = open("message2.txt", "r") #read mode
string = fobj.readline()
print(string)
fobj.close()
Hello How are You?
In [13]:
fobj = open("message2.txt", "r") #read mode
string = fobj.readline()
print(string)
string = fobj.readline()
print(string)
string = fobj.readline()
print(string)
string = fobj.readline()
print(string)
fobj.close()
Hello How are You? Hi I am fine Thankyou What are you doing
In [14]:
fobj = open("message2.txt", "r") #read mode
string = fobj.readline()
print(string, end='')
string = fobj.readline()
print(string)
string = fobj.readline()
print(string)
string = fobj.readline()
print(string)
fobj.close()
Hello How are You? Hi I am fine Thankyou What are you doing
In [15]:
fobj = open("message2.txt", "r") #read mode
string = fobj.readline(20)
print(string)
fobj.close()
Hello How are You?
In [ ]:
fobj = open("message2.txt", "r") #read mode
string = fobj.readline(10)
print(string)
fobj.close()
In [17]:
fobj = open("message2.txt", "r") #read mode
string = fobj.readline(10)
print(string)
string = fobj.readline(10)
print(string)
fobj.close()
Hello How are You?
In [18]:
fobj = open("message2.txt", "r") #read mode
string = fobj.readline(10)
print(string)
string = fobj.readline(10)
print(string)
string = fobj.readline()
print(string)
fobj.close()
Hello How are You? Hi I am fine
Reading all lines using loop and readline() method¶
In [ ]:
#readline with loop
fobj = open("message2.txt", "r") #read mode
line =' '
while line:
line = fobj.readline()
print(line, end='')
fobj.close()
In [ ]:
#readline with loop
fobj = open("message2.txt", "r") #read mode
while True:
line = fobj.readline()
if line == False:
break
print(line, end='')
fobj.close()
In [ ]:
#readline with loop
fobj = open("message2.txt", "r") #read mode
while True:
line = fobj.readline()
if line == False:
break
print(line, end='')
fobj.close()
In [ ]:
In [ ]:
#readline with loop
fobj = open("message2.txt", "r") #read mode
while True:
line = fobj.readline()
if line == False:
break
print(line, end='')
fobj.close()
Hello How are You? Hi I am fine Thankyou What are you doing I am taking online class
In [1]:
#readline with loop
fobj = open("message2.txt", "r") #read mode
while True:
line = fobj.readline()
if not line:
break
print(line, end='')
fobj.close()
Hello How are You? Hi I am fine Thankyou What are you doing I am taking online class
Using of with statment – with open()¶
In [5]:
def writeFile():
with open("content.txt", "w") as fobj:
fobj.write('Had an amazing time at the concert last night with @MusicLoversCrew.\n')
fobj.write('Excited to announce the launch of our new website!\n')
fobj.write('\n')
fobj.write('G20 @ India\n')
writeFile()
Write a functions which print lines having @ any where in the line¶
In [6]:
def COUNTLINES():
with open("content.txt", "r") as fobj:
line =' '
while line:
line = fobj.readline()
if '@' in line:
print(line, end='')
COUNTLINES()
Had an amazing time at the concert last night with @MusicLoversCrew. G20 @ India
Reading all lines using readlines()¶
In [7]:
#READLINES()
fobj = open("message.txt")
lines = fobj.readlines()
print(lines)
fobj.close()
['Hello How are You?Hi I am fineThankyou\n', 'anjeev singh is a best teacher']
In [8]:
#READLINES()
fobj = open("message2.txt")
lines = fobj.readlines()
print(lines)
fobj.close()
['Hello How are You?\n', 'Hi I am fine\n', 'Thankyou\n', 'What are you doing\n', 'I am taking online class\n']
In [9]:
#READLINES()
fobj = open("message2.txt")
lines = fobj.readlines()
for line in lines:
print(line, end='')
fobj.close()
Hello How are You? Hi I am fine Thankyou What are you doing I am taking online class
In [11]:
#READLINES()
fobj = open("content.txt")
lines = fobj.readlines()
for line in lines:
print(line, end='')
fobj.close()
Had an amazing time at the concert last night with @MusicLoversCrew. Excited to announce the launch of our new website! G20 @ India
In [12]:
#READLINES()
fobj = open("content.txt")
lines = fobj.readlines()
for line in lines:
if '@' in line:
print(line, end='')
fobj.close()
Had an amazing time at the concert last night with @MusicLoversCrew. G20 @ India
In [14]:
string = "hello how are you. how are you doing"
t = string.split()
print(t)
['hello', 'how', 'are', 'you.', 'how', 'are', 'you', 'doing']
In [ ]:
## Write a program to count occurence of 'how' in a file. Using read(), split() and count() functions
In [15]:
string = "hello how are you. how are you doing"
t = string.split()
n = t.count('how')
print(n)
2
In [ ]:
## Write a program to count word 'the' in the file using loop.
In [16]:
fobj = open("content.txt", "r")
data = fobj.read().split()
count = 0
for w in data:
if w == 'the':
count = count + 1
print(count)
fobj.close()
2
In [19]:
fobj = open("message2.txt", "r")
data = fobj.read().split()
count = data.count('you')
print(count)
fobj.close()
3
tell() and seek() function¶
In [1]:
# tell() function
fobj = open("message2.txt", "r")
print("Current position of cursor : ", fobj.tell())
word = fobj.read(6)
print(word)
print("Current position of cursor : ", fobj.tell())
data = fobj.read(5)
print(data)
print("Current position of cursor : ", fobj.tell())
fobj.close()
Current position of cursor : 0 Hello Current position of cursor : 6 How a Current position of cursor : 11
Write a program to find size of a file in bytes.¶
In [4]:
fobj = open("content.txt", "r")
data = fobj.read()
size = fobj.tell()
print("Size of file : ", size)
print(len(data))
fobj.close()
Size of file : 137 133
seek()¶
Jump the cursor at specified position. file_object.seek(byte, offset) Where offset specified the reference point. Three values can be given : 0 – beg 1 – current 2 – end Example: fobj.seek(10) # 10bytes ahead from beginning fobj.seek(-5, 1) # 5 bytes back from current fobj.seek(-5, 2) # b bytes back from end position
In [8]:
# tell() function
fobj = open("message2.txt", "r")
print("Current position of cursor : ", fobj.tell())
word = fobj.read(6)
print(word)
print("Current position of cursor : ", fobj.tell())
data = fobj.read(5)
print(data)
print("Current position of cursor : ", fobj.tell())
fobj.seek(6) #6bytes from beginning
print("Current position of cursor : ", fobj.tell())
data = fobj.read(4)
print("Current position of cursor : ", fobj.tell())
fobj.seek(25)
data = fobj.read(5)
print(data)
print("Current position of cursor : ", fobj.tell())
fobj.close()
Current position of cursor : 0 Hello Current position of cursor : 6 How a Current position of cursor : 11 Current position of cursor : 6 Current position of cursor : 10 am f Current position of cursor : 30
Binary File Handling in Python¶
In [11]:
import pickle
def writeRows():
fobj = open("student.dat", "wb")
n = int(input("How many records you want to add "))
for i in range(n):
r = int(input("Roll Number : "))
n = input("Name : ")
f = float(input("Fee : "))
rec = [r, n, f]
pickle.dump(rec, fobj)
fobj.close()
writeRows()
Reading a binary file¶
In [12]:
import pickle
def readRows():
fobj = open("student.dat", "rb")
while True:
rec = pickle.load(fobj)
print(rec)
fobj.close()
readRows()
[1, 'Ravi', 500.0] [2, 'Asha', 550.0]
--------------------------------------------------------------------------- EOFError Traceback (most recent call last) Cell In[12], line 9 6 print(rec) 7 fobj.close() ----> 9 readRows() Cell In[12], line 5, in readRows() 3 fobj = open("student.dat", "rb") 4 while True: ----> 5 rec = pickle.load(fobj) 6 print(rec) 7 fobj.close() EOFError: Ran out of input
In [17]:
import pickle
def readRows():
fobj = open("student.dat", "rb")
try:
while True:
rec = pickle.load(fobj)
print(rec)
except EOFError:
fobj.close()
readRows()
[1, 'Ravi', 500.0] [2, 'Asha', 550.0] [3, 'Shyam', 600.0] [4, 'Mohan', 450.0]
Appending Records in a Binary file¶
In [16]:
import pickle
def appendRecord():
fobj = open("student.dat", "ab") #ab => append binary
r = int(input("Roll Number : "))
n = input("Name : ")
f = float(input("Fee : "))
rec = [r, n, f]
pickle.dump(rec, fobj)
fobj.close()
appendRecord()
Searching a record in a binary file¶
In [18]:
# Display and count those records having fee less than 550
import pickle
def searchNcount():
fobj = open("student.dat", "rb")
count = 0
try:
while True:
rec = pickle.load(fobj)
if rec[2] < 550:
print(rec)
count = count + 1
except EOFError:
fobj.close()
print("Number of records : ", count)
searchNcount()
[1, 'Ravi', 500.0] [4, 'Mohan', 450.0] Number of records : 2
Updating a binary file¶
In [20]:
# Read, Check and Modify
In [22]:
#Write a function to increase the fee by 10% of those student having fee less than 550.
import pickle
def updateFee():
fobj = open("student.dat", "rb+") #for update open file in rb+ mode
count = 0
try:
while True:
beg_pos_rec = fobj.tell() #beginning position of record
rec = pickle.load(fobj)
if rec[2] < 550:
#print(rec)
rec[2] = rec[2] + rec[2] * 0.10
fobj.seek(beg_pos_rec) # jump the cursor at the beginning of the record
pickle.dump(rec, fobj)
count = count + 1
except EOFError:
fobj.close()
print("Number of records Modified : ", count)
updateFee()
Number of records Modified : 2
In [23]:
import pickle
def readRows():
fobj = open("student.dat", "rb")
try:
while True:
rec = pickle.load(fobj)
print(rec)
except EOFError:
fobj.close()
readRows()
[1, 'Ravi', 550.0] [2, 'Asha', 550.0] [3, 'Shyam', 600.0] [4, 'Mohan', 495.0]
In [ ]:
Download