0% found this document useful (0 votes)
64 views10 pages

File Handling

The document provides information on file handling in Python. It discusses input/output processes, different types of files like text and binary files, opening and closing files, reading from and writing to files, and absolute and relative paths. Examples are given of opening files in read, write, and append modes. The use of pickle module for binary files is demonstrated to write and read student data objects from a binary file. Classes are introduced to represent student objects that can be written to and read from files. CSV files are also discussed with an example of writing data to a CSV file using the csv module.

Uploaded by

Ashish Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views10 pages

File Handling

The document provides information on file handling in Python. It discusses input/output processes, different types of files like text and binary files, opening and closing files, reading from and writing to files, and absolute and relative paths. Examples are given of opening files in read, write, and append modes. The use of pickle module for binary files is demonstrated to write and read student data objects from a binary file. Classes are introduced to represent student objects that can be written to and read from files. CSV files are also discussed with an example of writing data to a CSV file using the csv module.

Uploaded by

Ashish Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

04/07/2022 Monday

File Handling

I/P → Process → O/P

Keyboard Monitor (console)


File Monitor
Keyboard File
File File

I/P from file → Reading a file


O/P to file → Writing to a file

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

Text File Binary File


Data is stored in ASCII format Data is store in binary format
Varying length record Fixed Length record
Single Mode operation Mixed Mode Operation
Forward Traversal Forward and Backward traversing
supported
16705 → 16705 → AA
1 →1 → ^A

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

file = open(“Story.txt”, “r”)

c:\Data\Python\Story.txt

..\..\data\Story.txt

file = open(“c:\\Data\\Python\\Story.txt”, “r”)


file = open(“..\\..\\data\\Story.txt”, “r”)

opening a file
open(filename, mode= ‘r’)

closing the file

filehandle.close()

file.close()
myfile.close()

Modes
r → read (input)
w → write (output)
a → append (output)
b → binary
+ → spouse

r+b rb+ br+ +rb b+r

r → Read / file must exists


w → Write / create a new file
file exists → delete old data and creates a new file
file doesn’t exists → Create a new file

a → Append (Write) / Adds data to the endfile


file exists → adds data at the end of the file
file doesn’t exists → Create a new file

read → read a character / string


readline → string
readlines → List of string

file = open(“filename.txt”, “r”)

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()

13/07/2022 → Binary File


import pickle
file = open(“filename.dat”, “rb”)
# read
data = pickle.load(file)
# write
pickle.dump(data, file)
file.close()

#program to write student data

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

dc = {“Rno”:1, “Name”:”pavan”, “marks”:75}

reclist=[{“Rno”:1, “Name”:”pavan”, “marks”:75},{“Rno”:2,


“Name”:”Amit”, “marks”:74.5}]

import os
os.system(“del employee.dat”)
os.system(“rename temp.dat employee.dat”)

file = open(“second.csv”, “r”)

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

You might also like