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

Python IO

  • 1.
  • 2.
    File Handling inPython  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  Wecan 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  Wecan 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  Toremove 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 andFolders  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  Wecan 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 removeFile  Rename the File  import os  os.rename("Test.txt","Demo.txt")  Remove The file  os.remove("Demo.txt") 10
  • 11.
    Writing to thefile  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 byline  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 fromthe 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 usingfor 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  Bydefault 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
  • 18.
  • 19.
    Serialization  Serialization isthe 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  classMobile:  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 intoa 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)  importpickle  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  Wheneverwe 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 isa 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
  • 26.