Text file
#demofile.txt (text file)
‘“Hello! My name is Riddhi.
Good Luck!”’
To open the file
f = open("demofile.txt", "r")
print(f.read())
output:
Hello! My name is Riddhi.
Good Luck!
Return the 5 first characters :
f = open("demofile.txt", "r")
print(f.read(5))
output:
Hello
Read one line:
f = open("demofile.txt", "r")
print(f.readline())
output:
Hello! My name is Riddhi.
Seek function:
f = open("demofile.txt", "r")
f.seek(4)
print(f.readline())
output:
o! My name is Riddhi
Tell function:
f = open("demofile.txt", "r")
print(f.readline())
print(f.tell())
output:
Hello! My name is Riddhi.
26
Open the file "demofile2.txt" and append
content:
f = open("demofile2.txt", "a")
f.write("roll.no 31")
f.close()
output:
Hello! My name is Riddhi.
Good Luck! roll.no 31
Open the file and overwrite the content:
f = open("demofile3.txt", "w")
f.write("I have deleted the content!")
f.close()
output:
I have deleted the content!
Csv file
#Data.csv (csv file)
“’Hello! My name is Riddhi.
Good Luck!”’
Read data
import csv as c:
with open(‘Data.csv’ , ‘r’) as m:
d=c.reader(m)
for i in d:
print(i)
output:
Hello! My name is Riddhi.
Good Luck!
Write data:
import csv as c:
with open(‘Data.csv’ , ‘w’) as m:
d=c.writer(m)
d.writerow(“roll no. 31”)
output:
Hello! My name is Riddhi.
Good Luck!
roll no. 31
binary file
load function:
import pickle:
with open(‘Data.dat’ , ‘rb’) as m:
x= pickle.load(m)
if x[2]== “My”:
print(x)
output:
Hello! My name is Riddhi.
Good Luck!
Dump function:
import pickle:
with open(‘Data.dat’ , ‘wb’) as m:
x= “roll no. 31”
pickle.dump(x, m)
output:
Hello! My name is Riddhi.
Good Luck!
roll no. 31