SlideShare ist ein Scribd-Unternehmen logo
1 von 26
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

Weitere ähnliche Inhalte

Was ist angesagt?

Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
Introduction to Linux, Pico, G++
Introduction to Linux, Pico, G++Introduction to Linux, Pico, G++
Introduction to Linux, Pico, G++
Michael Gordon
 
Mongo db勉強会20110730
Mongo db勉強会20110730Mongo db勉強会20110730
Mongo db勉強会20110730
Akihiro Okuno
 

Was ist angesagt? (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
 

Ähnlich wie Python IO

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
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 

Ähnlich wie 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
 
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
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 

Kürzlich hochgeladen

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Kürzlich hochgeladen (20)

How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 

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