File Handling
File Handling
File Handling
Opening a file
Read / write
Traversing a file
Closing the file
Types of Files:
1. Text Files → .txt, .rtf
2. Binary Files → .dat, .bin, .raw
3. CSV Files → Comma Separated Values
01000001 01000001
65 65
A A
1
00000000 00000001
0 1
--------------------------------------------------------------------------------------
05/07/2022 → Tuesday
Path
Absolute Path → starts from root, includes drive letter
Relative Path → does not include root
C:\
E:\
\ .. name
C:\----
|
+ ---- Data
| |
| + ----Python
| story.txt
+----- Programs
|
+ --- Games
|
+---- XII Project
Myproj.py
c:\Data\Python\Story.txt
..\..\data\Story.txt
opening a file
open(filename, mode= ‘r’)
filehandle.close()
file.close()
myfile.close()
Modes
r → read (input)
w → write (output)
a → append (output)
b → binary
+ → spouse
s = file.read()
s = file.read(10)
s = file.readline()
s = file.readline(20)
l = file.readlines()
l = file.readlines(200)
file.close()
write
writeline
12/07/2022 → Online
class Students:
def __init__(self, nm='', cl='', mk=0.0):
self.Name = nm
self.Class = cl
self.Marks = mk
def show(self):
print('Name: %-30s\tClass: %-5s\tMarks: %5.1f' %(self.Name,
self.Class, self.Marks))
a = Students()
b = Students('Pavan', 'XII', 76.567)
a.show()
b.show()
import pickle
file = open(“student.dat”, “ab”)
lst = [1, “pavan”, 75.5]
pickle.dump(lst, file)
lst = [2, “anil”, 74, “science”]
pickle.dump(lst, file)
file.close()
import pickle
file = (“student.dat”, “rb”)
data = pickle.load(file)
print(data)
data1= pickle.load(file)
print(data1)
data2 = pickle.load(file) → error
s = file.read(1)
while s:
print(s)
s = file.read()
import pickle
file = open(“student.dat”, “rb”)
while True:
try:
data = pickle.load(file)
print(data)
except EOFError:
break
14/07/2022 → Thursday
class Student :
def __init__(self, rno=0, name=””, marks=0.0):
self.rno = rno
self.name = name
self.marks = marks
def read(self):
self.rno = int(input(“Enter the roll no:”))
self.name = input(“Enter the name:”)
self.marks = float(input(“Enter the marks:”))
def print(self):
print(“%04d\t%-30s\t%6.2f” %(self.rno, self.name,
self.marks))
a = Student()
b = Student(5,”Anil”,55.5)
c = Student()
c.read()
a.print()
b.print()
c.print()
lst=[…]
for i in range(len(lst)):
lst[i]
for x in lst:
x
import os
os.system(“del employee.dat”)
os.system(“rename temp.dat employee.dat”)
import csv
with open(“second.csv”, “w”) as file:
writeobj = csv.writer(file, “,”)
while True:
rno=int(input(“Enter roll no.”))
name=input(“Enter name”))
marks=float(input(“Enter marks”))
writeobj.writerow(rno,name,marks)
choice = input(“Do you ant more ? Y/N”
if choice.upper() != ”Y”:
break