SlideShare a Scribd company logo
1
File Handling
File Handling in Python
 We have two types of data storage:
 Persistent: permanent storage.
 Transient: temporary storage.
 We can store data permanently in a file with the help of
python.
 We can read that data from a file later.
write read
2
Types of Data
 Text Data:
 Human Readable Data
 For ex. .txt, .py files
 Binary Data:
 Not human readable
 For ex. .mp3, .jpg, .png files
3
Create directories
 We can create folders with the help of os module in
python.
 If you are not providing path, than it will create the
folder in the current working directory.
 import os
 os.mkdir("D:/MyFolder")
 Create Multiple directories:
 os.makedirs("My/Python/Folder")
4
Rename folders
 We can provide exact location where we want to save it
after renaming the folder.
 os.rename("D:/MyFolder","D:/Folder")
 OR we can give just new name of the folder, after that it
will create the folder in the same working directory.
 os.rename("D:/folder","Myfolder")

MyFolder Folder
rename
5
Remove Folders
 To remove a single Directory:
 import os
 os.rmdir("D:/MyFolder")
 To remove multiple directories:
 import os
 os.removedirs("My/Python/Folder")
 It will remove all, if all the directories are empty
 If folders are not empty, than only empty folder will be
deleted not all.
6
List Files and Folders
 We can list files and folders of a specified directory.
 If you are not providing the directory path than it will return
list from the current working directory.
 import os
 list=os.listdir("D:/")
 i=1
 for e in list:
 print("{} {}".format(i,e))
 i+=1
7
To get path, sub Directories, and files
 import os
 for path,subFolder,files in os.walk("D:/MyDir"):
 for name in files:
 print(name)
8
File Operation
 We can perform basic file operation in python.
 Open() function is used to open the file object in different
mode.
 When we are opening a file in writing mode , and file does
not exist, than it will create a new file in specified path.
 And opens a file in writing mode.
 file=open("Test.txt","w")
 print("File is ready to write")
9
Rename and remove File
 Rename the File
 import os
 os.rename("Test.txt","Demo.txt")
 Remove The file
 os.remove("Demo.txt")
10
Writing to the file
 file=open("Test.txt","w")
 print("File is ready to write")
 #write 5 lines
 for x in range(1,5):
 file.write("Hello {}".format(x))
 file.close()
 print("File is closed")
11
Write line by line
 file=open("Test.txt","w")
 print("File is ready to write")
 for x in range(1,5):
 #file.write("Hello {}n".format(x))#or
 file.writelines("Hello {}n".format(x))
 file.close()
 print("File is close")
12
Read Data from the file
 file=open("Test.txt","r")
 # read all file data at once
 data=file.read()
 # read only 5 characters
 data=file.read(5)
 # read a single line
 data=file.readline()
 # returns a list containing comma separated lines
 data=file.readlines()
 print(data)
 file.close()
13
Read Data using for Loop
 Read data line by line from a file.
 file=open("Test.txt","r")
 for line in file:
 print(line)
14
Copy Image file
 We can read and write binary data too.
 source=open("Indore.jpg","rb")
 dest=open("CopyIndore.jpg","wb")
 data=source.read()
 dest.write(data)
 source.close()
 dest.close()
 print("File copied")
15
File Attribute
 By default it will open in reading mode
 file=open("Test.txt")
 print("File Name:",file.name)
 print("File mode:",file.mode)
 print("File is closed:",file.closed)
16
File pointer’s Position
 Tell(): tell method returns the file pointer location
 Seek(int): we can reposition the file pointer
 file=open("Test.txt","r")
 print("File pointer Location ",file.tell())
 #read all data, pointer will reach to the EOF
 print(file.read())
 #now repoistion to the 1st position
 file.seek(0)
 file.close()
17
Serialization and Deserialization
18
Serialization
 Serialization is the process to convert the object into
byte stream.
 We can send the object to a file, network , Data base
after that.
 pickle module is used to write the serialized object into
the file.
19
Mobile class
 class Mobile:
 def __init__(self,color,price, brand):
 self.__color = color
 self.__price = price
 self.__brand = brand
 def get_price(self):
 return self.__price
 def get_brand(self):
 return self.__brand
 def get_color(self):
 return self.__color
20
Write Object into a file
 import pickle
 file=open("Mobile.ser","wb")
 pickle.dump(Mobile,file)
 file.close()
 print("Object state saved into a file")
21
Read Object(Deserialization)
 import pickle
 file=open("Mobile.ser","rb")
 mobileObj=pickle.load(file)
 print("Brand ",mobileObj.get_brand())
 print("Color ",mobileObj.get_color())
 print("Price ",mobileObj.get_price())
22
Resource Management
 Whenever we open a file we have to close it.
 When we open a file using a with statement then we do
not need it close it by close method.
 The file is automatically closed when the bock is finished.
 The file will auto close when the with block will finish the
execution
 with open("Test.txt") as file:
 for lines in file:
 print(lines)
 print("Is file closed ?",file.closed)
23
File Operation Modes
 r:
 opens a file in reading mode. It is a default mode.
 w:
 if file exist open it in writing mode, if not then it will create it.
 a:
 open file in append mode.
 rb:
 open a binary file in reading mode.
 wb:
 open a binary file in writing mode.
 ab:
 open a binary file in appending mode.
 r+:
 reading writing both
 w+:
 reading writing both
24
Disclaimer
 This is a educational Presentation to make
programming easier.
 We have used images of different URLs to make
presentation better.
 We respect the work of the owners of the URLs.
25
Thank You!
:rtstech30@gmail.com
:+91 8818887087

More Related Content

What's hot

Linux basic1&2
Linux basic1&2Linux basic1&2
Linux basic1&2
Hideo Amezawa
 
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentationsupporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
Mahabubur Rahaman
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2ADARSH BHATT
 
Introduction to Linux, Pico, G++
Introduction to Linux, Pico, G++Introduction to Linux, Pico, G++
Introduction to Linux, Pico, G++Michael Gordon
 
Basic linux commands for bioinformatics
Basic linux commands for bioinformaticsBasic linux commands for bioinformatics
Basic linux commands for bioinformatics
Bonnie Ng
 
File system
File systemFile system
File system
Gayane Aslanyan
 
Files in c++
Files in c++Files in c++
Files in c++
NivethaJeyaraman
 
Python Files
Python FilesPython Files
Python Files
Vikram Nandini
 
Linux basic commands with examples
Linux basic commands with examplesLinux basic commands with examples
Linux basic commands with examples
abclearnn
 
Exmaples of file handling
Exmaples of file handlingExmaples of file handling
Exmaples of file handling
sparkishpearl
 
Basics of Unix Adminisration
Basics  of Unix AdminisrationBasics  of Unix Adminisration
Basics of Unix Adminisration
Venkateswarlu Malleboina
 
Python and MongoDB
Python and MongoDBPython and MongoDB
Python and MongoDB
Christiano Anderson
 
Mongo db勉強会20110730
Mongo db勉強会20110730Mongo db勉強会20110730
Mongo db勉強会20110730Akihiro Okuno
 
MongoDB-SESSION03
MongoDB-SESSION03MongoDB-SESSION03
MongoDB-SESSION03
Jainul Musani
 
Archlinux install
Archlinux installArchlinux install
Archlinux install
sambismo
 
C++ files and streams
C++ files and streamsC++ files and streams
C++ files and streams
krishna partiwala
 
Linux commd
Linux commdLinux commd
Linux commd
ragav03
 
Object
ObjectObject

What's hot (20)

Linux basic1&2
Linux basic1&2Linux basic1&2
Linux basic1&2
 
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentationsupporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
Introduction to Linux, Pico, G++
Introduction to Linux, Pico, G++Introduction to Linux, Pico, G++
Introduction to Linux, Pico, G++
 
Basic linux commands for bioinformatics
Basic linux commands for bioinformaticsBasic linux commands for bioinformatics
Basic linux commands for bioinformatics
 
File system
File systemFile system
File system
 
Files in c++
Files in c++Files in c++
Files in c++
 
Python Files
Python FilesPython Files
Python Files
 
Linux basic commands with examples
Linux basic commands with examplesLinux basic commands with examples
Linux basic commands with examples
 
Latinoware
LatinowareLatinoware
Latinoware
 
Exmaples of file handling
Exmaples of file handlingExmaples of file handling
Exmaples of file handling
 
File handling
File handlingFile handling
File handling
 
Basics of Unix Adminisration
Basics  of Unix AdminisrationBasics  of Unix Adminisration
Basics of Unix Adminisration
 
Python and MongoDB
Python and MongoDBPython and MongoDB
Python and MongoDB
 
Mongo db勉強会20110730
Mongo db勉強会20110730Mongo db勉強会20110730
Mongo db勉強会20110730
 
MongoDB-SESSION03
MongoDB-SESSION03MongoDB-SESSION03
MongoDB-SESSION03
 
Archlinux install
Archlinux installArchlinux install
Archlinux install
 
C++ files and streams
C++ files and streamsC++ files and streams
C++ files and streams
 
Linux commd
Linux commdLinux commd
Linux commd
 
Object
ObjectObject
Object
 

Similar to Python IO

Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
File Handling in python.docx
File Handling in python.docxFile Handling in python.docx
File Handling in python.docx
manohar25689
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
kendriyavidyalayano24
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
Lifna C.S
 
ExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdf
aquacare2008
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
files.pptx
files.pptxfiles.pptx
files.pptx
KeerthanaM738437
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
Automate the boring stuff with python
Automate the boring stuff with pythonAutomate the boring stuff with python
Automate the boring stuff with python
DEEPAKSINGHBIST1
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
Files.pptx
Files.pptxFiles.pptx
Files.pptx
Govardhan Bhavani
 
Python data file handling
Python data file handlingPython data file handling
Python data file handling
ToniyaP1
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
SakhilejasonMsibi
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
armaansohail9356
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 

Similar to Python IO (20)

Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
File Handling in python.docx
File Handling in python.docxFile Handling in python.docx
File Handling in python.docx
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
ExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdf
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
files.pptx
files.pptxfiles.pptx
files.pptx
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Automate the boring stuff with python
Automate the boring stuff with pythonAutomate the boring stuff with python
Automate the boring stuff with python
 
Files in c++
Files in c++Files in c++
Files in c++
 
Files.pptx
Files.pptxFiles.pptx
Files.pptx
 
Python data file handling
Python data file handlingPython data file handling
Python data file handling
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 

Recently uploaded

Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 

Recently uploaded (20)

Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 

Python IO

  • 2. File Handling in Python  We have two types of data storage:  Persistent: permanent storage.  Transient: temporary storage.  We can store data permanently in a file with the help of python.  We can read that data from a file later. write read 2
  • 3. Types of Data  Text Data:  Human Readable Data  For ex. .txt, .py files  Binary Data:  Not human readable  For ex. .mp3, .jpg, .png files 3
  • 4. Create directories  We can create folders with the help of os module in python.  If you are not providing path, than it will create the folder in the current working directory.  import os  os.mkdir("D:/MyFolder")  Create Multiple directories:  os.makedirs("My/Python/Folder") 4
  • 5. Rename folders  We can provide exact location where we want to save it after renaming the folder.  os.rename("D:/MyFolder","D:/Folder")  OR we can give just new name of the folder, after that it will create the folder in the same working directory.  os.rename("D:/folder","Myfolder")  MyFolder Folder rename 5
  • 6. Remove Folders  To remove a single Directory:  import os  os.rmdir("D:/MyFolder")  To remove multiple directories:  import os  os.removedirs("My/Python/Folder")  It will remove all, if all the directories are empty  If folders are not empty, than only empty folder will be deleted not all. 6
  • 7. List Files and Folders  We can list files and folders of a specified directory.  If you are not providing the directory path than it will return list from the current working directory.  import os  list=os.listdir("D:/")  i=1  for e in list:  print("{} {}".format(i,e))  i+=1 7
  • 8. To get path, sub Directories, and files  import os  for path,subFolder,files in os.walk("D:/MyDir"):  for name in files:  print(name) 8
  • 9. File Operation  We can perform basic file operation in python.  Open() function is used to open the file object in different mode.  When we are opening a file in writing mode , and file does not exist, than it will create a new file in specified path.  And opens a file in writing mode.  file=open("Test.txt","w")  print("File is ready to write") 9
  • 10. Rename and remove File  Rename the File  import os  os.rename("Test.txt","Demo.txt")  Remove The file  os.remove("Demo.txt") 10
  • 11. Writing to the file  file=open("Test.txt","w")  print("File is ready to write")  #write 5 lines  for x in range(1,5):  file.write("Hello {}".format(x))  file.close()  print("File is closed") 11
  • 12. Write line by line  file=open("Test.txt","w")  print("File is ready to write")  for x in range(1,5):  #file.write("Hello {}n".format(x))#or  file.writelines("Hello {}n".format(x))  file.close()  print("File is close") 12
  • 13. Read Data from the file  file=open("Test.txt","r")  # read all file data at once  data=file.read()  # read only 5 characters  data=file.read(5)  # read a single line  data=file.readline()  # returns a list containing comma separated lines  data=file.readlines()  print(data)  file.close() 13
  • 14. Read Data using for Loop  Read data line by line from a file.  file=open("Test.txt","r")  for line in file:  print(line) 14
  • 15. Copy Image file  We can read and write binary data too.  source=open("Indore.jpg","rb")  dest=open("CopyIndore.jpg","wb")  data=source.read()  dest.write(data)  source.close()  dest.close()  print("File copied") 15
  • 16. File Attribute  By default it will open in reading mode  file=open("Test.txt")  print("File Name:",file.name)  print("File mode:",file.mode)  print("File is closed:",file.closed) 16
  • 17. File pointer’s Position  Tell(): tell method returns the file pointer location  Seek(int): we can reposition the file pointer  file=open("Test.txt","r")  print("File pointer Location ",file.tell())  #read all data, pointer will reach to the EOF  print(file.read())  #now repoistion to the 1st position  file.seek(0)  file.close() 17
  • 19. Serialization  Serialization is the process to convert the object into byte stream.  We can send the object to a file, network , Data base after that.  pickle module is used to write the serialized object into the file. 19
  • 20. Mobile class  class Mobile:  def __init__(self,color,price, brand):  self.__color = color  self.__price = price  self.__brand = brand  def get_price(self):  return self.__price  def get_brand(self):  return self.__brand  def get_color(self):  return self.__color 20
  • 21. Write Object into a file  import pickle  file=open("Mobile.ser","wb")  pickle.dump(Mobile,file)  file.close()  print("Object state saved into a file") 21
  • 22. Read Object(Deserialization)  import pickle  file=open("Mobile.ser","rb")  mobileObj=pickle.load(file)  print("Brand ",mobileObj.get_brand())  print("Color ",mobileObj.get_color())  print("Price ",mobileObj.get_price()) 22
  • 23. Resource Management  Whenever we open a file we have to close it.  When we open a file using a with statement then we do not need it close it by close method.  The file is automatically closed when the bock is finished.  The file will auto close when the with block will finish the execution  with open("Test.txt") as file:  for lines in file:  print(lines)  print("Is file closed ?",file.closed) 23
  • 24. File Operation Modes  r:  opens a file in reading mode. It is a default mode.  w:  if file exist open it in writing mode, if not then it will create it.  a:  open file in append mode.  rb:  open a binary file in reading mode.  wb:  open a binary file in writing mode.  ab:  open a binary file in appending mode.  r+:  reading writing both  w+:  reading writing both 24
  • 25. Disclaimer  This is a educational Presentation to make programming easier.  We have used images of different URLs to make presentation better.  We respect the work of the owners of the URLs. 25