03-01-File Handling
03-01-File Handling
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.
Opening Files in Python (cont… ) 1
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.
Opening Files in Python (cont… ) 5
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read(5))
Output:
Hello
method.
Reading Information in the File (cont…3)
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read())
Output:
Hello World
Hello Python
Good Morning
Here we have not provided any argument
inside the read() function. Hence it will read all
the content present inside the file.
Reading Information in the File (cont…4)
Example 3:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline(2))
Output:
He
Example 4:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())
Output:
Hello World
Example 5:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readlines())
Output:
*‘Hello World\n’, ‘Hello Python\n’, ‘Good Morning’+
Output:
Hello World
Hello Python
Good Morning
How are You
Write to a Python File
• In order to write data into a file, we must open the file
in write mode.
• We need to be very careful while writing data into the file
as it overwrites the content present inside the file that
you are writing, and all the previous data will be erased.
• We have two methods for writing data into a file as
shown below.
– write(string)
– writelines(list)
• Example 1:
my_file = open(“C:/Documents/Python/test.txt”,
“w”) my_file.write(“Hello World”)
The above code writes the String ‘Hello World’ into the ‘test.txt’
file.
Write to a Python File (cont…1)
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World\n”)
my_file.write(“Hello Python”)
• The first line will be ‘Hello World’ and as we have mentioned \n character,
the cursor will move to the next line of the file and then write ‘Hello Python’.
• Remember if we don’t mention \n character, then the data will be
written continuously in the text file like ‘Hello WorldHelloPython’
Example 3:
fruits = *“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”+
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.writelines(fruits)
The above code writes a list of data into the ‘test.txt’ file simultaneously.
Append in a Python File
To append data into a file we must open the file in
‘a+’ mode so that we will have access to both
the append as well as write modes.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”,
“a+”) my_file.write (“Strawberry”)
The above code appends the string ‘Strawberry’ at the end of the ‘test.txt’ file
Example 2:
my_file = open(“C:/Documents/Python/test.txt”,
“a+”) my_file.write (“\nGuava”)
WhenNOW youPRESS
run ANY
the above code,
program will stopped at “Press any
KEY…. Now content is stored,
key”, for time being don’t press any because of close() function
key and go to folder where file contents are flushed and
“temp.txt” is created an open it to see pushed in file
f l u s h ( ) f u n c ti o n … . cont.. 2
All contents before flush() are present in
E x a m p l e : w o r k i n g of f l u s h ( )
With flush()
ch = myfile.read(1
ch will store first character i.e. first character is
consumed, and file pointer will move to next character
B i n a r y f i l e o p e rat i o n s
• If we want to write a structure such as list or
dictionary to a file and read it subsequently
we need to use the Python module pickle.
Pickling is the process of converting structure
to a byte stream before writing to a file and
while reading the content of file a reverse
process called Unpickling is used to convert
the byte stream back to the original format.
B i n a r y f i l e o p e ra t i o n s cont…1
• Example: dump()
See the content is some kind of encrypted format, and it is not in complete readabl
Binar fil o p e ra t i o cont…
• Example: load()
Binar fil o p e ra t i o cont…
In student.csv (notepad) file, the first line is the header and remaining lines are the data/
records. The fields are separated by comma. In general, the separator character is called a
delimiter, and the comma is not the only one used. Other popular delimiters include the tab
(\t), colon (:) and semi-colon (;) characters.
CSV File operations in Python Cont…04_b
Program to read the contents of “student.csv” file
Code uses “with open()” function, the only difference being that the
file being opened using with open() gets automatically closed after the
program execution gets over, unlike open() where we need to give
close() statement explicitly.