SlideShare a Scribd company logo
1 of 25
File Handling
File
A file or a computer file is a chunk of logically related
data or information which can be used by computer
programs.
File is categorized as either text or binary.
• Text File- Text files are structured as a sequence of
lines, where each line includes a sequence of
characters
• Binary File- A binary file is any type of file that is
not a text file.
Hence, in Python, a file operation takes place in the
following order.
• Open a file
• Read or write (perform operation)
• Close the file
The open Function
• Python's built-in open() function is used to open the file.
Syntax: fileobject=open(“filename”,”mode”,”buffering”)
• File name: The file name argument is a string value
• Access mode: The access mode determines the mode in which the file has to be opened. The modes are
• Buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is
performed while accessing a file.
Write to file
Example: main.py
Write () Method:- The write() method writes any string to an open file.
fo = open("foo.txt", "w")
fo.write("Welcome!!")
fo.close()
Writelines() Method:- Writes a sequence of strings to the file.
fo = open("foo.txt", "w")
lines=["hi all ","good morning"," bye"]
fo.writelines(lines)
fo.write("n KCE")
fo.close()
Read From file
Example: main.py
Read () Method:-It is used to read the data from the file.
fo = open("foo.txt", "r")
print(fo.read())
fo.close()
Readline() Method:-It is used to read a single line from the file.
fo = open("foo.txt", "r")
print(fo.readline())
fo.close()
Readlines() Method:-It is used to read many number of lines from the file.
fo = open("foo.txt", "r")
print(fo.readlines())
fo.close()
The file Object Attributes
• Once a file is opened and you have one file object, We can get various information related to that file.
>>>fo = open("foo.txt", "w")
>>>print("Name of the file: ", fo.name)
>>>print("Closed or not : ", fo.closed)
>>>print("Opening mode : ", fo.mode)
Name of the file: foo.txt
Closed or not : False
Opening mode : w
Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
Looping over a file object
• When you want to read – or return – all the lines from a file in a more memory efficient, and fast manner,
you can use the loop over method.
Example:
f = open("foo.txt", "r")
for line in f:
print(line)
f=open("kathir","w")
f.writelines("EEEnECEnITnCSnETEnMECH")
f.close()
f=open("kathir","r")
for i in f.readlines():
k=i.split()
for j in k:
print(j)
f.close()
f=open('h1','w')
f.writelines("ExcellentnGoodnBetter
")
f.close()
f=open('h1','r')
for i in f:
print(f.read())
f.close()
With Statement
• user can also work with file objects using the with statement.
• One bonus of using this method is that any files opened will be closed automatically after you are done.
Syntax: - with open(“filename”) as file:
Example:
with open("hello.txt", "w") as f:
f.write("Hello World")
with open("w1.txt", "w") as f:
f.write("1n2n3n4")
with open("w1.txt", "r") as f:
total=0
for line in f:
num = int(line)
total += num
print("sum",total)
File Positions
• tell() :- The tell() method tells the current position within the file.
Syntax: fileobject.tell()
fo = open("foo.txt", "w")
fo.write("Welcome to the world of jumangi n mayajal")
fo.close()
fo=open("foo.txt",'r')
print(fo.tell())
print(fo.read(6))
print(fo.tell())
File Positions cont..
• seek() :- This method changes the current file position. f.seek(0,2)- gives the total no of characters in a given file
• The offset argument indicates the number of bytes to be moved.
Syntax:
fileobject.seek(offset)
fo = open("foo.txt", "w")
fo.write("Welcome to the world of jumangi n mayajal")
fo.close()
fo=open("foo.txt",'r')
print(fo.seek(23))
print(fo.read())
f=open('h1','w')
f.write("I love this
worldn")
f.writelines("Course Plus
n the Full Specialization
n Shareable Certificates")
#print(f.truncate(7))
f.close()
f=open('h1','r')
print(f.seek(0,2))
f.close()
File methods
• A file object is created using open function and here is a list of functions which can be called on this object
character=input("Enter the character to find its
occurrence")
f=open("input.txt","r")
count=0
for line in f:
for i in line:
if i.casefold()==character:
count=count+1
print("{} occurs {}" .format(character,count))
f.close()
f=open("input.txt","r")
count=0
for line in f:
for i in line.split():
count=count+1
print("occurs {}" .format(count))
f.close()
word=input("Enter the word you want to
count")
f=open("input.txt","r")
count=0
for line in f:
for i in line.split():
if i.casefold()==word:
count=count+1
print("{}occurs {}" .format(word,count))
f.close()
Number of words in the given text file
f=open("input.txt","r")
counts = list()
count=0
for lines in f:
words=lines.split()
for word in words:
counts.append(word)
if word in counts:
count=count+1
else:
count=1
print(“occurs”,count)
Number of specific word in the given text file
class FileIO(Exception):
def fun(self):
print("Error! No such file." )
try:
def exists(filename):
try:
f = open(filename)
f.close()
return True
except IOError:
return False
fn=input("enter your file name")
print(fn)
x=exists(fn)
print(x)
if x == True:
print("carry on with your file operation")
f=open(fn)
print(f.read())
else:
raise FileIO
except FileIO as e:
fo=open(“input.txt","r")
counts = dict()
for lines in fo:
words=lines.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
print(counts)
f=open('h1','w')
f.writelines("Course Plus n the Full
Specialization n Shareable Certificates")
f.close()
try:
f=open('h2','r')
for i in f:
print(f.read())
f.close()
except Exception as e:
print (e)
File methods cont…
Example :
fileno ( ):-
fo = open(“foo.txt", "w")
print ("Name of the file: ", fo.name)
print ("File Descriptor: ", fo.fileno())
fo.close()
next()
fd=open("hari.txt","r")
for index in range(1,3):
line=next(fd,-1)
print(index,line)
Pickle
• It is used for serializing and de-serializing a Python object structure.
• Pickling is a way to convert a python object (list, tuple, set, dictionary) into a
character stream import the module through this command:
• import pickle has two main methods: dump() and load().
Dump()-Used to dumps an object to a file object
Load()-Used to loads an object from a file object.
Syntax:
pickle.dump(value,fileobject)
variable=pickle.load(fileobject)
Example
import pickle
f1=open("pickle1.txt","wb")
#list,set,tuple,dictionary
set={10:'ram',20:'raj',30:'sam'}
pickle.dump(set,f1)
f1.close()
f2=open("pickle1.txt","rb")
list2=pickle.load(f2)
print("in tuple",list2)
f2.close()
Class object Serialization
class Employee:
def __init__(self,Empid=None,Empname=None,Empsalary=None):
self.__Empid=Empid
self.__Empname=Empname
self.__Empsalary=Empsalary
def get_empid(self):
return self.__Empid
def get_empname(self):
return self.__Empname
def get_empsalary(self):
return self.__Empsalary
def set_empid(self, value):
self.__Empid = value
def set_empname(self, value):
self.__Empname = value
def set_empsalary(self, value):
self.__Empsalary = value
def __repr__(self):
return "Employee id {}nEMployee Name {}nEmployee
Salary{}".format(self.get_empid(),self.get_empname(),self.get_empsalary())
import pickle
f1=open("f1.txt","wb")
li=[[101,'sam',25000],[125,"Bob",145000]]
for i in li:
obj=Employee()
obj.set_empid(i[0])
obj.set_empname(i[1])
obj.set_empsalary(i[2])
pickle.dump(obj,f1)
f1.close()
f2=open("f1.txt","rb")
for i in range(len(li)):
dobj=pickle.load(f2)
print(dobj)
f2.close()
2
1
3
4
5
Create a student object having properties name, date of
birth, department, semester.
Let the employee class have appropriate getter/setters
methods for accessing these properties.
Initialize these properties through the setter methods.
Store this object into a file "OutObject.txt".
Read the same object from the same file and display its
properties through getter methods.
Shelve
• It is used for serializing and de-serializing a Python object structure.
• In pickle random access of an object is not possible where as it is possible
using shelve.
• The shelve module can be used as a simple persistent storage option
for Python objects when a relational database is overkill. The shelf is
accessed by keys, just as with a dictionary.
• The values are pickled and written to a database created and managed by
anydbm
Example :
import shelve
s=shelve.open("file1.txt","c")
l1=[10,20,30]
l2=[30,40]
s["lis1"]=l1[1]
for i,j in s.items():
print (i,j)
'c' flag tells shelve to open the file for reading and writing

More Related Content

Similar to files.pptx

File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptRaja Ram Dutta
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in pythonLifna C.S
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdfRashmiAngane1
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16Vishal Dutt
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugevsol7206
 
Python data file handling
Python data file handlingPython data file handling
Python data file handlingToniyaP1
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C ProgrammingRavindraSalunke3
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Rex Joe
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxssuserd0df33
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfsangeeta borde
 
Python programming
Python programmingPython programming
Python programmingsaroja20
 

Similar to files.pptx (20)

Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
Python - Lecture 8
Python - Lecture 8Python - Lecture 8
Python - Lecture 8
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
 
Python Session - 5
Python Session - 5Python Session - 5
Python Session - 5
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Python File functions
Python File functionsPython File functions
Python File functions
 
Python data file handling
Python data file handlingPython data file handling
Python data file handling
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
Files in c++
Files in c++Files in c++
Files in c++
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files.pptx
Files.pptxFiles.pptx
Files.pptx
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
Python programming
Python programmingPython programming
Python programming
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 

Recently uploaded

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Recently uploaded (20)

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 

files.pptx

  • 1. File Handling File A file or a computer file is a chunk of logically related data or information which can be used by computer programs. File is categorized as either text or binary. • Text File- Text files are structured as a sequence of lines, where each line includes a sequence of characters • Binary File- A binary file is any type of file that is not a text file. Hence, in Python, a file operation takes place in the following order. • Open a file • Read or write (perform operation) • Close the file
  • 2. The open Function • Python's built-in open() function is used to open the file. Syntax: fileobject=open(“filename”,”mode”,”buffering”) • File name: The file name argument is a string value • Access mode: The access mode determines the mode in which the file has to be opened. The modes are • Buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file.
  • 3. Write to file Example: main.py Write () Method:- The write() method writes any string to an open file. fo = open("foo.txt", "w") fo.write("Welcome!!") fo.close() Writelines() Method:- Writes a sequence of strings to the file. fo = open("foo.txt", "w") lines=["hi all ","good morning"," bye"] fo.writelines(lines) fo.write("n KCE") fo.close()
  • 4. Read From file Example: main.py Read () Method:-It is used to read the data from the file. fo = open("foo.txt", "r") print(fo.read()) fo.close() Readline() Method:-It is used to read a single line from the file. fo = open("foo.txt", "r") print(fo.readline()) fo.close() Readlines() Method:-It is used to read many number of lines from the file. fo = open("foo.txt", "r") print(fo.readlines()) fo.close()
  • 5. The file Object Attributes • Once a file is opened and you have one file object, We can get various information related to that file. >>>fo = open("foo.txt", "w") >>>print("Name of the file: ", fo.name) >>>print("Closed or not : ", fo.closed) >>>print("Opening mode : ", fo.mode) Name of the file: foo.txt Closed or not : False Opening mode : w Attribute Description file.closed Returns true if file is closed, false otherwise. file.mode Returns access mode with which file was opened. file.name Returns name of the file.
  • 6. Looping over a file object • When you want to read – or return – all the lines from a file in a more memory efficient, and fast manner, you can use the loop over method. Example: f = open("foo.txt", "r") for line in f: print(line)
  • 7. f=open("kathir","w") f.writelines("EEEnECEnITnCSnETEnMECH") f.close() f=open("kathir","r") for i in f.readlines(): k=i.split() for j in k: print(j) f.close() f=open('h1','w') f.writelines("ExcellentnGoodnBetter ") f.close() f=open('h1','r') for i in f: print(f.read()) f.close()
  • 8. With Statement • user can also work with file objects using the with statement. • One bonus of using this method is that any files opened will be closed automatically after you are done. Syntax: - with open(“filename”) as file: Example: with open("hello.txt", "w") as f: f.write("Hello World")
  • 9. with open("w1.txt", "w") as f: f.write("1n2n3n4") with open("w1.txt", "r") as f: total=0 for line in f: num = int(line) total += num print("sum",total)
  • 10. File Positions • tell() :- The tell() method tells the current position within the file. Syntax: fileobject.tell() fo = open("foo.txt", "w") fo.write("Welcome to the world of jumangi n mayajal") fo.close() fo=open("foo.txt",'r') print(fo.tell()) print(fo.read(6)) print(fo.tell())
  • 11. File Positions cont.. • seek() :- This method changes the current file position. f.seek(0,2)- gives the total no of characters in a given file • The offset argument indicates the number of bytes to be moved. Syntax: fileobject.seek(offset) fo = open("foo.txt", "w") fo.write("Welcome to the world of jumangi n mayajal") fo.close() fo=open("foo.txt",'r') print(fo.seek(23)) print(fo.read())
  • 12. f=open('h1','w') f.write("I love this worldn") f.writelines("Course Plus n the Full Specialization n Shareable Certificates") #print(f.truncate(7)) f.close() f=open('h1','r') print(f.seek(0,2)) f.close()
  • 13. File methods • A file object is created using open function and here is a list of functions which can be called on this object
  • 14. character=input("Enter the character to find its occurrence") f=open("input.txt","r") count=0 for line in f: for i in line: if i.casefold()==character: count=count+1 print("{} occurs {}" .format(character,count)) f.close()
  • 15. f=open("input.txt","r") count=0 for line in f: for i in line.split(): count=count+1 print("occurs {}" .format(count)) f.close() word=input("Enter the word you want to count") f=open("input.txt","r") count=0 for line in f: for i in line.split(): if i.casefold()==word: count=count+1 print("{}occurs {}" .format(word,count)) f.close() Number of words in the given text file f=open("input.txt","r") counts = list() count=0 for lines in f: words=lines.split() for word in words: counts.append(word) if word in counts: count=count+1 else: count=1 print(“occurs”,count) Number of specific word in the given text file
  • 16. class FileIO(Exception): def fun(self): print("Error! No such file." ) try: def exists(filename): try: f = open(filename) f.close() return True except IOError: return False fn=input("enter your file name") print(fn) x=exists(fn) print(x) if x == True: print("carry on with your file operation") f=open(fn) print(f.read()) else: raise FileIO except FileIO as e:
  • 17. fo=open(“input.txt","r") counts = dict() for lines in fo: words=lines.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 print(counts)
  • 18. f=open('h1','w') f.writelines("Course Plus n the Full Specialization n Shareable Certificates") f.close() try: f=open('h2','r') for i in f: print(f.read()) f.close() except Exception as e: print (e)
  • 20. Example : fileno ( ):- fo = open(“foo.txt", "w") print ("Name of the file: ", fo.name) print ("File Descriptor: ", fo.fileno()) fo.close() next() fd=open("hari.txt","r") for index in range(1,3): line=next(fd,-1) print(index,line)
  • 21. Pickle • It is used for serializing and de-serializing a Python object structure. • Pickling is a way to convert a python object (list, tuple, set, dictionary) into a character stream import the module through this command: • import pickle has two main methods: dump() and load(). Dump()-Used to dumps an object to a file object Load()-Used to loads an object from a file object. Syntax: pickle.dump(value,fileobject) variable=pickle.load(fileobject)
  • 23. Class object Serialization class Employee: def __init__(self,Empid=None,Empname=None,Empsalary=None): self.__Empid=Empid self.__Empname=Empname self.__Empsalary=Empsalary def get_empid(self): return self.__Empid def get_empname(self): return self.__Empname def get_empsalary(self): return self.__Empsalary def set_empid(self, value): self.__Empid = value def set_empname(self, value): self.__Empname = value def set_empsalary(self, value): self.__Empsalary = value def __repr__(self): return "Employee id {}nEMployee Name {}nEmployee Salary{}".format(self.get_empid(),self.get_empname(),self.get_empsalary()) import pickle f1=open("f1.txt","wb") li=[[101,'sam',25000],[125,"Bob",145000]] for i in li: obj=Employee() obj.set_empid(i[0]) obj.set_empname(i[1]) obj.set_empsalary(i[2]) pickle.dump(obj,f1) f1.close() f2=open("f1.txt","rb") for i in range(len(li)): dobj=pickle.load(f2) print(dobj) f2.close() 2 1 3 4 5
  • 24. Create a student object having properties name, date of birth, department, semester. Let the employee class have appropriate getter/setters methods for accessing these properties. Initialize these properties through the setter methods. Store this object into a file "OutObject.txt". Read the same object from the same file and display its properties through getter methods.
  • 25. Shelve • It is used for serializing and de-serializing a Python object structure. • In pickle random access of an object is not possible where as it is possible using shelve. • The shelve module can be used as a simple persistent storage option for Python objects when a relational database is overkill. The shelf is accessed by keys, just as with a dictionary. • The values are pickled and written to a database created and managed by anydbm Example : import shelve s=shelve.open("file1.txt","c") l1=[10,20,30] l2=[30,40] s["lis1"]=l1[1] for i,j in s.items(): print (i,j) 'c' flag tells shelve to open the file for reading and writing