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
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
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