Python File Handling

File Handling

As the part of programming requirement, we have to store our data permanently for future purpose. For this requirement we should go for files.

Files are very common permanent storage areas to store our data.

Types of Files:
There are 2 types of files

  1. Text Files:Usually we can use text files to store character data eg: abc.txt
  2. Binary Files:Usually we can use binary files to store binary data like images,video files, audio files etc…

Opening a File:

Before performing any operation (like read or write) on the file, first we have to open that file. For this we should use Python’s inbuilt function open()

But at the time of open, we have to specify mode, which represents the purpose of opening file.

f = open(filename, mode)

The allowed modes in Python are

r: open an existing file for read operation. The file pointer is positioned at the beginning of the file. If the specified file does not exist then we will get FileNotFoundError.This is default mode.
w:  open an existing file for write operation. If the file already contains some data then it will be overridden. If the specified file is not already available then this mode will create that file.
a : open an existing file for append operation. It won't override existing data. If the specified file is not already available then this mode will create a new file.
r+ : To read and write data into the file. The previous data in the file will not be deleted. The file pointer is placed at the beginning of the file.
w+ : To write and read data. It will override existing data.
a+ : To append and read data from the file. Itwon’t override existing data.
x :  To open a file in exclusive creation mode for write operation. If the file already exists then we will get FileExistsError.

Note: All the above modes are applicable for text files. If the above modes suffixed with ‘b’ then these represents for binary files.

Ex: rb,wb,ab,r+b,w+b,a+b,xb

f = open(“abc.txt”,”w”)

We are opening abc.txt file for writing data.

Closing a File:

After completing our operations on the file,it is highly recommended to close the file.

For this we have to use close() function.

f.close()

Various properties of File Object:

Once we opened a file and we got file object, we can get various details related to that file by using its properties.

name: Name of opened file
mode: Mode in which the file is opened
closed: Returns boolean value indicates that file is closed or not
readable(): Returns boolean value indicates that whether file is readable or not writable()? Returns
Boolean: value indicates that whether file is writable or not.

Ex:
f=open(“abc.txt”,’w’)
print(“File Name: “,f.name)
print(“File Mode: “,f.mode)
print(“Is File Readable: “,f.readable())
print(“Is File Writable: “,f.writable())
print(“Is File Closed : “,f.closed)
f.close()
print(“Is File Closed : “,f.closed)

Output
D:\Python_classes>py test.py
File Name: abc.txt
File Mode: w
Is File Readable: False
Is File Writable: True
Is File Closed : False
Is File Closed : True

Writing data to text files:

We can write character data to the text files by using the following 2 methods.

write(str)
writelines(list of lines)

Ex:
f=open(“abcd.txt”,’w’)
f.write(“Dharshi\n”)
f.write(“Technology\n”)
f.write(“Companies\n”)
print(“Data written to the file successfully”)
f.close()

abcd.txt:
Dharshi
Technology
Companies

Note:

In the above program, data present in the file will be overridden every time if we run the program. Instead of overriding if we want append operation then we should open the file as follows.

f = open(“abcd.txt”,”a”)

Reading Character Data from text files:

We can read character data from text file by using the following read methods.

read(): To read total data from the file
read(n): To read 'n' characters from the file
readline(): To read only one line
readlines(): To read all lines into a list

The with statement:

  • The with statement can be used while opening a file. We can use this to group file operation statements within a block.
  • The advantage of with statement is it will take care closing of file, after completing all operations automatically even in the case of exceptions also, and we are not required to close explicitly.

Ex:
with open(“abc.txt”,”w”) as f:
f.write(“Dharshi\n”)
f.write(“Technology\n”)
f.write(“Companies\n”)
print(“Is File Closed: “,f.closed)
print(“Is File Closed: “,f.closed)

Output
Is File Closed: False
Is File Closed: True

The seek() and tell() methods:

tell():

  • We can use tell() method to return current position of the cursor(file pointer) from beginning of the file. [ can you plese telll current cursor position]
  • The position(index) of first character in files is zero just like string index.

Ex:
f=open(“abc.txt”,”r”)
print(f.tell())
print(f.read(2))
print(f.tell())
print(f.read(3))
print(f.tell())

abc.txt:
sunny
bunny
chinny
vinny

Output:
0
su
2
nny
5

seek():

We can use seek() method to move cursor(file pointer) to specified location. [Can you please seek the cursor to a particular location]

f.seek(offset, fromwhere)
offset represents the number of positions

The allowed values for second attribute(from where) are
0---->From beginning of file(default value)
1---->From current position
2--->From end of the file

Ex:
data=”All Students are STUPIDS”
f=open(“abc.txt”,”w”)
f.write(data)
with open(“abc.txt”,”r+”) as f:
text=f.read()
print(text)
print(“The Current Cursor Position: “,f.tell())
f.seek(17)
print(“The Current Cursor Position: “,f.tell())
f.write(“GEMS!!!”)
f.seek(0)
text=f.read()
print(“Data After Modification:”)
print(text)

Output
All Students are STUPIDS
The Current Cursor Position: 24
The Current Cursor Position: 17
Data After Modification:
All Students are GEMS!!!

How to check a particular file exists or not?

  • We can use os library to get information about files in our computer.
  • os module has path sub module,which contains isFile() function to check whether aparticular file exists or not?
os.path.isfile(fname)

Q. Write a program to check whether the given file exists or not. If it is available then print its content?
import os,sys
fname=input(“Enter File Name: “)
if os.path.isfile(fname):
print(“File exists:”,fname)
f=open(fname,”r”)
else:
print(“File does not exist:”,fname)
sys.exit(0)
print(“The content of file is:”)
data=f.read()
print(data)

Output
D:\Python_classes>py test.py
Enter File Name: shishir.txt
File does not exist: shishir.txt
D:\Python_classes>py test.py
Enter File Name: abc.txt
File exists: abc.txt
The content of file is:
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!

Note:

sys.exit(0) ===>To exit system without executing rest of the program.
argument represents status code . 0 means normal termination and it is the default value.

Handling Binary Data:

It is very common requirement to read or write binary data like images,video files,audio files etc.

Q. Program to read image file and write to a new image file?
f1=open(“rossum.jpg”,”rb”)
f2=open(“newpic.jpg”,”wb”)
bytes=f1.read()
f2.write(bytes)
print(“New Image is available with the name: newpic.jpg”)

Handling csv files:

CSV==>Comma seperated values

As the part of programming, it is very common requirement to write and read data wrt csv files. Python provides csv module to handle csv files.

Zipping and Unzipping Files:

It is very common requirement to zip and unzip files.

The main advantages are:

  • To improve memory utilization
  • We can reduce transport time
  • We can improve performance.

To perform zip and unzip operations, Python contains one in-bulit module zip file. This module contains a class : ZipFile

To create Zip file:
We have to create ZipFile class object with name of the zip file,mode and constant ZIP_DEFLATED. This constant represents we are creating zip file.

f = ZipFile("files.zip","w","ZIP_DEFLATED")

Once we create ZipFile object,we can add files by using write() method.

f.write(filename)

Ex:
from zipfile import *
f=ZipFile(“files.zip”,’w’,ZIP_DEFLATED)
f.write(“file1.txt”)
f.write(“file2.txt”)
f.write(“file3.txt”)
f.close()
print(“files.zip file created successfully”)

To perform unzip operation:
We have to create ZipFile object as follows

f = ZipFile("files.zip","r",ZIP_STORED)

ZIP_STORED represents unzip operation. This is default value and hence we are not required to specify.

Once we created ZipFile object for unzip operation,we can get all file names present in that zip file by using namelist() method.

names = f.namelist()

Ex:
from zipfile import *
f=ZipFile(“files.zip”,’r’,ZIP_STORED)
names=f.namelist()
for name in names:
print( “File Name: “,name)
print(“The Content of this file is:”)
f1=open(name,’r’)
print(f1.read())
print()

Follow Us On