You are on page 1of 18

File Handling In

Python
18103097 Parijat Garg
18103122 Atul Kumar

Your Logo or Name Here


Need For File Handling

Real life problems handle


large volumes of data

Hence, we need storage


devices such as hard disk,
DVD etc.

Data is stored in these


devices using the concept
of files

Your Logo or Name Here


What is a file??

File is a named Where a sequence Can be transferred


place on a disk of related data is to other storage
stored. devices.

Like flash drives , DVDs


etc.

Your Logo or Name Here 3


TYPES OF FILES IN PYTHON

TEXT FILES BINARY FILES

• Sequence of characters in human • Information is contained in the same


readable form. format as it is held in memory.
• Each line is terminated by a special • No delimiter for a line.
character known as EOL i.e \n , \r etc. • It is faster and easier for a program to
• Translations occur while reading a text read binary files than text files since no
file. translations occur.
• Occupies larger space is file is written in • Occupies lesser space than the text
text mode. mode.

Your Logo or Name Here


Operations On A File

CREATE OPEN READ WRITE UPDATE CLOSE

Your Logo or Name Here


OPEN function in
Python
To open a file in Python, built – in open
open(file, mode =‘r’, buffering = -1, encoding = None, errors = function is used.
None, newline = None, closefd= True, opener = None)
This function creates a file object which
would be utilized to call other support
methods associated with it.

• First argument = file path


• Second argument = mode in which the
file must be handled.

Your Logo or Name Here


A list of the different modes of opening a file

Modes Description

r Opens a file for reading only. The file pointer is placed at the beginning of the file. This
is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning
of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer will be at the beginning of the
file.
rb+ Opens a file for both reading and writing in binary format. The file pointer will be at the
beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If
the file does not exist, creates a new file for reading and writing.

Your Logo or Name Here


A list of the different modes of opening a file

a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for writing.

ab Opens a file for appending in binary format. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not exist, it creates a new
file for writing.

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the
file exists. The file opens in the append mode. If the file does not exist, it creates a new file
for reading and writing.

ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end
of the file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.

Your Logo or Name Here


Reading from files
f.read(size)

Lorem ipsum dolor sit


amet, consectetuer
adipiscing elit

Networked API
Lorem ipsum dolor sit
amet, consectetuer
adipiscing elit

Your Logo or Name Here


Example :
fo = open("foo.txt", "r")
str = fo.read(10);
print("Read String is : ", str)
fo.close()

This would produce following result:


Read String is : Python is

Example :
fo = open("foo.txt", "r")
print(f.readline())
print(f.readline(5))
fo.close()

This would produce following result:


Python is awesome
This is Your Logo or Name Here 10
Example :
fo = open("foo.txt", "r")
print(f.readlines())
fo.close()

This would produce following result:


[‘Python is awesome\n’, ‘This is a demo.\n’]

Example :
fo = open("foo.txt", "r")
print(f.readlines(10))
fo.close()

This would produce following result:


[‘Python is awesome\n’]

Your Logo or Name Here


write()

 The write() method writes any string to an open file. It is important


to note that Python strings can have binary data and not just text.
 The write() method does not add a newline character ('\n') to the
end of the string:
Syntax:
fileObject.write(string)

writelines()
 For a list of string elements, each string is inserted in the text
file.Used to insert multiple strings at a single time.
Syntax:
File_object.writelines(L) for L = [str1, str2, str3]
Your Logo or Name Here
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris\n","This is London \n"] This would produce following result:
file1.writelines(L)
file1.close()
Output of Readlines after appending
file1 = open("myfile.txt","a")#append mode ['This is Delhi \n', 'This is Paris \n', 'This is
file1.write("Today \n") London \n', 'Today \n']
file1.close()

file1 = open("myfile.txt","r")
Output of Readlines after writing
print ("Output of Readlines after appending“) ['Tomorrow \n']
print (file1.readlines())
print()
file1.close()

file1 = open("myfile.txt","w")#write mode


file1.write("Tomorrow \n")
file1.close()

file1 = open("myfile.txt","r")
print ("Output of Readlines after writing“)
print( file1.readlines() )
print() Your Logo or Name Here
file1.close()
File Output
• File objects have additional built-in methods. Say I have the file
object f:
• f.tell()gives current position in the file.
• f.seek(offset[, from]) offsets the position by offset
bytes from from position.
• In text files, only seeks relative to the beginning of the file are
allowed except seek(0, 2) and the only valid offset values are
those returned from the f.tell(), or zero

Your Logo or Name Here


Example:
fo = open("foo.txt", "r+")
str = fo.read(10);
print ("Read String is : ", str)
position = fo.tell();
print ("Current file position : ", position)
position = fo.seek(0, 0);
str = fo.read(7);
print ("Again read String is : ", str)
fo.close()

• This would produce following result:


Read String is : Python is
Current file position : 10
Again read String is : Python
Your Logo or Name Here
file.flush() file.close()

• Python holds the data to write in


• this method will be used to close the file
the file in a buffer and pushes it
object once we have finished working with
onto the storage a little later.
it.
• We can use flush() to force Python
to write the content of buffer into • It will free up all system resources used by
the storage. the object

• Python automatically flushes the


files when closing them i. e the • Python automatically closes a file when
function is implicitly called by the reference object of a file is assigned to
close. another file.

Your Logo or Name Here


The file object atrributes:
Once a file is opened and you have one file object, you can get various
information related to that file.

Here is a list of all attributes related to file object:

Attribute Description
file.closed Returns true if file is closed, false otherwise.

file.mode Returns access mode with which file was opened.

file.name Returns name of the file.

Your Logo or Name Here


THANK YOU
 ANY QUERY!

Your Logo or Name Here

You might also like