0% found this document useful (0 votes)
25 views23 pages

File Handling

Uploaded by

Payal Govindani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views23 pages

File Handling

Uploaded by

Payal Govindani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

File Handling in

Python
Files
• Files are named locations on disk to store related
information. They are used to permanently store
data in a non-volatile memory (e.g. hard disk).
• Since Random Access Memory (RAM) is volatile
(which loses its data when the computer is turned
off), we use files for future use of the data by
permanently storing them.
• When we want to read from or write to a file, we
need to open it first. When we are done, it needs
to be closed so that the resources that are tied
with the file are freed.
• Hence, in Python, a file operation takes place in
the following order:
– Open a file
– Read or write (perform operation)
– Close the file
Text Files and Binary
Files
Types Of File in Python

• There are two types of files in


Python and each of them are
explained below in detail with
examples for your easy
understanding. They are:

• Binary file
• Text file
Binary files in Python
• All binary files follow a specific format.
We can open some binary files in the
normal text editor but we can’t read the
content present inside the file. That’s
because all the binary files will be
encoded in the binary format, which
can be understood only by a computer
or machine.
• For handling such binary files we need a
specific type of software to open it.
• For Example, You need Microsoft word
software to open .doc binary files.
Likewise, you need a pdf reader
software to open .pdf binary files and
you need a photo editor software to
read the image files and so on.
Binary files in Python (cont…1)
• Most of the files that we see in our
computer system are called binary
files.
• Example:
• Document files: .pdf, .doc, .xls etc.
• Image files: .png, .jpg, .gif, .bmp etc.
• Video files: .mp4, .3gp, .mkv, .avi etc.
• Audio files: .mp3, .wav, .mka, .aac etc.
• Database files: .mdb, .accde, .frm, .sqlite
etc.
• Archive files: .zip, .rar, .iso, .7z etc.
• Executable files: .exe, .dll, .class etc.
Text files in Python
• A text file is usually considered as
sequence of lines. Line is a sequence of
characters (ASCII), stored on permanent
storage media. Although default
character coding in python is ASCII but
supports Unicode as well.
• in text file, each line is terminated by a
special character, known as End of Line
(EOL). From strings we know that \n is
newline character.
• at the lowest level, text file is collection
of bytes. Text files are stored in human
readable form.
• they can also be created using any text
editor.
Text files in Python (Cont…1)
• Text files don’t have any specific
encoding and it can be opened in
normal text editor itself.
• Example:
• Web standards: html, XML, CSS, JSON
etc.
• Source code: c, app, js, py, java etc.
• Documents: txt, tex, RTF etc.
• Tabular data: csv, tsv etc.
• Configuration: ini, cfg, reg etc.
Opening or Creating a New File
in Python
• The method open() is used to open an existing file or creating a new file. If the complete directory is
not given then the file will be created in the directory in which the python file is stored. The syntax for
using open() method is given below.
– Syntax:

– file_object = open( file_name, “Access Mode”,


Buffering )
• The open method returns file object which
can be stored in the name file_object (file-
handle).
• File name is a unique name in a directory.
The open() function will create the file with
the specified name if it is not already exists
otherwise it will open the already existing
file.
• The access mode
it is the string which tells in what mode the file should be opened for operations. There are three different
access modes are available in python.

• Reading: Reading mode is crated only for


reading the file. The pointer will be at the
beginning of the file.
• Writing: Writing mode is used for
overwriting the information on existing
file.
• Append: Append mode is same as the
writing mode. Instead of over writing the
information this mode append the
information at the end.
• Below is the list of representation of various access modes in python.
Access modes in Text Files
• ‘r' – Read Mode: Read mode is used only
to read data from the file.
• ‘w' – Write Mode: This mode is used when you want to write data into the file or modify it.
Remember write mode overwrites the data present in the file.

• ‘a' – Append Mode: Append mode is


used to append data to the file.
Remember data will be appended at the
end of the file pointer.
• ‘r+' – Read or Write Mode: This mode is
used when we want to write or read the
data from the same file.
• ‘a+' – Append or Read Mode: This mode
is used when we want to read data from
the file or append the data into the same
file.
Access modes in Binary Files
• ‘wb’ – Open a file for write only
mode in the binary format.
• ‘rb’ – Open a file for the read-only
mode in the binary format.
• ‘ab’ – Open a file for appending only
mode in the binary format.
• ‘rb+’ – Open a file for read and write
only mode in the binary format.
• ‘ab+’ – Open a file for appending
and read-only mode in the binary
format.
What is Buffering ?
• Buffering is the process of storing a
chunk of a file in a temporary
memory until the file loads
completely. In python there are
different values can be given. If the
buffering is set to 0
, then the buffering is off. The
buffering will be set to 1 when we
need to buffer the file.
Examples Opening a file:

# open file in current directory


• f = open("test.txt“, “r”)

# specifying full path


• f = open(r“D:\temp\data.txt“, “r”)
– –raw string
• f = open(“D:\\temp\\data.txt“, “r”)
– -absolute path
Closing Files in Python
• After processing the content in a file,
the file must be saved and closed. To do
this we can use another method close()
for closing the file. This is an important
method to be remembered while
handling files in python.
• Syntax: file_object.close()

string = "This is a String in


Python" my_file =
open(my_file_name.txt,"w+",1)
my_file.write(string)
my_file.close()
print(my_file.closed)
Reading Information in the File

• In order to read a file in python, we


must open the file in read mode.
• There are three ways in which we
can read the files in python.
– read([n])
– readline([n])
– readlines() – all lines returned to a list
• Here, n is the number of bytes to be
read.
Example 1:

my_file =
open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read(5))

Output:

Hello

• Here we are opening the file test.txt in a


read-only mode and are reading only the
first 5 characters of the file using the
my_file.read(5) method.
Example 2:

my_file =
open(“C:/Documents/Python/t
est.txt”, “r”)
print(my_file.read())
Output:

H
e
l
l
o
W
o
r
l
d
H
e
l
l
o
P
y
t
h
o
n
G
o
o
d
M
o
r
n
i
n
g
Here we have not
provided any
argument inside the
read() function.
Hence it will read all
the content present
inside the file.

You might also like