Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

File Handling

Need for a data file:File handling allows us to store data


on disk and also retrieve it whenever we need. Example:
File:File is a bunch or stream or sequence of
bytes/characters stored on storage device. Output:
Types of file: Syntax: File_object.read([n] )
i. Text files (Consists Data in ASCII Human readable form
each line end with special character EOL)
Example:
ii. Binary files(Consists Data in Binary form)
iii Comma Separated File-CSV Output:
Text file:Basic operations on a text file:
a) Create/Open of a File
Through open (Filename,[Filemode]) function we create Example:
a new file or open an existing file and the function returns
a file object. Output:
Filemode Syntax: File_object.readline([n])
Text Binar How File Exists File does
File y File Opened not exist
Mode Mode
“r” “rb” Read Opens the Error
only file
“w” “wb” Write Clears the file Creates Example:
only contents and opens
a new file
“a” “ab” Write File contents Creates Output:
only left intact and opens Syntax: File_object.readlines( )
and new data a new file
appended at
file’s end
“r+” “rb+” Read Reads and Error
and overwrites
Write from the file’s
Example:
beginning Output:
“w+” “wb+” Read Clears the file Creates
and contents and opens
write a new file
“a+” “ab+” Read File contents Creates c) Writing to Data File:
and left intact and opens
write and read and a new file  write (string): It takes a sting as argument and
write at file’s adds to the file. We have to use ‘\n’ in string for
end end of line character.
Syntax:  writelines (sequence of lines): If we wantto
file_object=open(filename) OR open(filename,filemode) write list, tuple into the file then we usewritelines.
Example:Relative path: Syntax: File_object.write(string )
f=open(“test1.txt”) or open(“test1.txt”,”r”) Example:
Absolute path:f=open(“d:\\file handling\\test1.txt”) or
f=open(“d:\\file handling\\test1.txt”,”r”)
b) Reading from File :
 read( ) Reads all or some bytes from the file and
returns it as a string.
Output: Hello.txt (Notepad file)
 readline( ) Reads a line at a time.
 readlines() Reads all the lines from the file and
returns it in the form of a list. Syntax:File_object.writelines(List )
Syntax: File_object.read([n] ) Example:

Example: Output:Data.txt (Notepad file)

Output:

1
d) Appending data: Binary file:
If we want to add contents after the previously added Binary files store data in the binary format (0’s and
contents then we need to open file in append mode. 1’s) machine understandable form. When we open
demofile.txt the binary file, it decodes the data and displays in a
Hello! Welcome to demofile.txt human-readable format.
This file is for testing purposes. Basic operations with binary file:
Good Luck! a) Create/Open of a File : Through open
Example: (Filename,[Filemode]) function we create a new file
f = open("demofile.txt", "a") or open an existing file and the function returns a
f.write("Now the file has more content!") file object.
f.close() Syntax: file_object = open(filename,filemode)
f = open("demofile.txt", "r") Example:Relative path:
print(f.read()) f=open(“test1.dat”,”rb”)
Output:demofile.txt (Notepad file) f=open(“test1.dat”,”wb”)
Hello! Welcome to demofile.txt Absolute path:
This file is for testing purposes. f=open(“d:\\file handling\\test1.dat”,”rb”) OR
Good Luck!Now the file has more content! f=open(“d:\\file handling\\test1.dat”,”wb”)
e) Deletion of the file: remove() function with os module Pickle Module
os.remove() Pickle module is used to read/write Python
Example: import os sequence (List,Dictionary etc) with mixed data type
os.remove("demofile.txt") from/to binary file.
f) Close File:close() funtion Pickling-Convert sequence into byte stream.
Syntax: file_object.close( )Example: f. close( ) Unpickling- Convert byte stream into sequence
Standard file streams Pickle Method:dump( ) : To write Object into the file
Standard devices use as Standard Streams use them by Syntax : pickle.dump(object_to_write,file_object)
sys module.Three input/output (I/O) streams are :
 Standard input (stdin) -sys.stdin (read from
standard input device-keyboard )
 Standard output(stdout) -sys.stdout (Write to Example:
Standard Output device-monitor) Output:ListData.dat file10,20,30,40
 Standard error (stderr) -sys.stderr (Contains Error load( ) : To read the Object from the file
Messages) Syntax : container_obj=pickle.load(file_object)

Example:
Output:[10,20,30,40]
b)Write data to a Binary File:
fout=open("test1.dat","wb")
str1= "My First Binary File"
str2= str1.encode ("ASCII")
fout.write(str2)
Relative and absolute path fout.close( ) Output:test1.dat file My First Binary File
A relative path defines a location that is relative to the c) Read the data from Binary File:
current directory or folder. fin=open("test1.dat","rb")
An absolute path is the full address of any file or folder str1= fin.read( )
from the drive that is from root folder. str2 =str1.decode("ASCII")
drivename:\folder\folder\filename. print(str2)
OS module provides many such functions which can be fin.close( ) Output: My First Binary File
used to work with files and directories. OS means d) Write list to a Binary File
Operating System. L1 = [23, 43, 55, 10, 90]
getcwd( ) is a very function which can be used to identify F= open("test1.dat", "wb") F.write(bytearray(L1))
the current working directory. F.close() Output:test1.dat file 23 43 55 10 90
import os e)Read list from Binary File
>>>curr_dir=os.getcwd() F= open("test1.dat", "rb") L1=list(F.read())
>>> print(curr_dir) F.close()
print(L1) Output:[23, 43, 55, 10, 90]
2
f)Read and write pdf from/to Binary File k)Search operations in a binary file
F1 = open("p1.pdf", "wb") import pickle
F2 = open("p2.pdf", "rb") std=[ ]
W1= F2.read( ) f=open("std.dat","rb")
F1.write(W1) a='y'
F1.close( ) stdid=int(input("Enter std id:"))
F2.close( ) Output:Above Code will make another copy of grasp=False
P2.pdf with new name P1.pdf while True:
g)Read and write pdf from/to Binary File try:
F1 = open("P1.jpg", "rb") std=pikcle.load(f)
F2 = open("P2.jpg", "wb") except EOFERROR:
W1 = F1.read( ) break
F2.write(W1) print("%10s"%"Std ID","%20s"%"Std Name")
F1.close( ) for S in std:
F2.close( ) Output:Above Code will make another copy of if(S[0]==stdid:
P1.pdf with new name P2.pdf for S in std:
h)Write Dictionary to a Binary File if(S[0]==stdid:
import pickle print("%10s"%S[0],"%20s"%S[1])
D1 = {‘name’:’Swati’,’lname’:’Srivastava’} Grasp=True
F= open("test1.dat", "wb") break
pickle.dump(D1,F) if Grasp ==False:
F.close( ) Output:test1.dat file Swati Srivastava print("Student ID not found")
i) Read Dictionary from Binary File f.close()
import pickle CSV (Comma Separated Values)
F= open("test1.dat", "rb") A CSV file is a type of plain text file that uses specific
D1=pickle.load(F) structuring to arrange tabular data.(.csv extension)
print(“Binary File with dictionary is”,D1) Emp No., Emp Name ,Emp Dept, Emp Sal
F.close( )Output:Binary File with dictionary 1, Swati, Science, 80000
is{‘name’:’Swati’,’lname’:’Srivastava’} 2, Rajesh, commerce, 75000
j)Update operations in a binary file. Working with CSV files we should import CSV
Example: module.
exists_word =input("Input word replaced: ").encode() a)Read data from CSV file:To read data from a CSV
new_word =input("\nEnter the new word: ").encode() file, we have to use reader( ) function.
string = b"" Reader( ):function takes each row of the file and
Flag = 0 make a list of all columns.
with open('test1.dat', 'r + b') as file: Example:
pos = 0 Import csv
data = string = file.read(1) with open('C:\\test1.csv','rt') as F:
while data: data = csv.reader(F)
data = file.read(1) for row in data:
if data == b" ": print(row)
if string == exists_word:
file.seek(pos) b)Write data to a CSV file:
file.write(new_word) writer( ): Write data in a CSV file use writer( ).
Flag = 1 writerow( ) To iterate the data over the rows (lines),
break you have to use the writerow( ) function.
else: Example:
pos = file.tell() import csv
data = string = file.read(1) with open('C:\\data.csv', mode='a', newline='') as
else: file:
string += data writer =csv.writer(file, delimiter=',', quotechar='"'
continue )
if Flag: writer.writerow(['3', 'Swati', 'Computer', '85000'])
print("Record successfully updated") writer.writerow(['4', 'Rajesh', 'IP', '90000'])
else:
print("Record not found")

3
Question and Answers Q6. Write a method in python to write multiple
Q 1.Answer the questions that follow lines of text contents into a text file myfile.txt
File = open("Mydata","a") ________________ #Blank1
File.close() def write1( ):
(i) What type (Text/Binary) of file is Mydata? f = open("myfile.txt","w")
(ii) Fill in Blank 1 with a statement to write “ABC” in the file
while True:
“Mydata”.
line = input("Enter line")
Ans. (i) Text File (ii) File.write("ABC")
f.write(line)
Q2.WAP to count total words in a text file.
choice = input("Are there more lines")
Ans:c=0
if choice == "N":
f1=open("a.txt")
break
for w in f1.read().split():
f.close()
c=c+1
Q7.Differentiate between file modes r+ and rb+
print("word count ",c)
with respect to Python
f1.close()
Q3. Difference between r+ and w+. r+ rb+
Opens a file for both Opens a file for both
r+ w+
Opens a file for both Opens a file for both writing
reading and writing. reading and writing
reading and writing. The and reading. The file pointer placed In binary format. The
file pointer placed at the Overwrites the existing file if at the beginning of the file pointer placed at
beginning of the file. the file exists. If the file does file. the beginning of the
not exist, creates a new file for file.
reading and writing. Q8.Consider a binary file “Emp.dat”
Q4. Write a method in Python to read lines from a text containingdetails such as
file MYNOTES.TXT, and display those lines, which are empno:ename:salary(separator ‘:’). Write a python
starting with the alphabet ‘K’. function to display details of those employees who
Ans: def display (): are earning between 20000 and 40000
file=open('MYNOTES.TXT',”r”) fin=open("emp.dat")
line=file.readline ( ) x=fin.readline()
while line: while x:
if line[0]=='K' : data=x.split(":")
print(line) if(float(data[2])>20000<30000):
line=file.readline ( ) print(data)
file.close ( ) x=fin.readline()
display() fin.close()
Q5.Considering the following definition FACTORY, write Q9. Write a python program to copy file1.txt into
a method in Python to search and display the content in file2.txt.
a pickled file FACTORY.DAT, where FCTID is matching fin=open("file1.txt")
with the value ―’105’. fout=open("file2.txt","w")
Ans: def in it (self, FID, FNAM): data=fin.read()
self. FCTID = FID fout.write(data)
self. FCTNM = FNAM fin.close()
self. PROD = 1000 fout.close()
def Display(self): Q10.Read the code given below and answer the
print (self. FCTID,":" self. FCTNM,":", self. PROD) question:
import pickle F1 =open(“first.txt”,”w”)
def answer ( ): F1.write(“Welcome”)
f=Factory ( ) F1.close()
file=open('FACTORY.DAT','rb') If the file contains “kvs” before execution, what will
try: be the contents of file after execution of the above
while True: code
f=pickle.load(file) Ans: The file now contains only “Welcome” because
if f.FCTID==105: when the file is opened in writing mode, it truncates
f.Display() the existing data in the file.
except EOF Error:
pass
file.close ( )

You might also like