0% found this document useful (0 votes)
8 views

Text and Binary File-1

Uploaded by

niranjananetra10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Text and Binary File-1

Uploaded by

niranjananetra10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

File Handling

 Files help in storing information permanently.


 A file in itself is a bunch of bytes stored on
some storage devices like hard disk, thumb
drive etc.
 A file is a document or the data stored on a
permanent storage device which can be read,
written or rewritten according to requirement.
Data Files
 Data files are the files that store data
pertaining to a specific application for later
use. Data files can be stored in two ways.
 Text Files
 Binary Files
Text Files
 A text file stores information in ASCII or
Unicode characters.
 In text files each line of text is terminated
with a special character known as EOL(End Of
Line).
 In text files some internal translations takes
place when this EOL character is read or
written.
 In python this EOL character is the newline
character(‘\n’),or carriage return.
Binary File
 A binary file is a file that contains the
information in the same format in which the
information held in the memory ie the binary
form.
 In a binary file there is no delimiter for a line.
 Also no internal translations occur in binary
files.
 As a result, the binary files are faster and
easier for a program to read and write than
the text files.
Opening and closing files
 In order to work with a file, from within a
python program, we need to open it in a
specific mode as per the file manipulation task
we want to perform.
 The basic file manipulation task include:
reading data from the file
writing data to the file
appending data to a file.
 Python provides built-in functions to perform
each of these tasks.
Opening files
 The first thing that we do in file handling is
opening the file.
Syntax
file object name=open(<”file name”>)
file object name=open(<”file name”>,<mode>)
eg:- myfile=open(“taxes.txt”)
This statement opens file “taxes.txt” in file
mode as read mode (default mode)and
attaches it to the file object namely myfile.
eg:-file2=open(“data.txt”,”r”)
This statement opens the file “data.txt” in
read mode and attaches it to file object
namely file2.
eg:- file3=open(“e:\\main\\result.txt”,”w”)
Python will look for this file in e:\\ main folder.
This statement opens the file “result.txt” in
write mode and attaches it to file object
namely file3.
 Open() function creates a file object which
serves as a link to a file residing on the
computer.
 The first parameter for the open() is a path to
the file which we want to open. If just the file
name is given, then Python searches for the
file in the current folder.
 The 2nd parameter of the open()corresponds
to a mode ‘r’ or’w’ or any other modes.
f= open(r“c:\temp\data.txt”,”r”)
The prefix ‘r’ in front of a string makes it raw
string that means there is no special meaning
attached to any character.
 f= open(“c:\temp\data.txt”,”r”)
This statement might give you incorrect result
as \t is a tab character and \d in some
platforms performs as a numeric-digit.
 Thus two ways to give paths in filenames
correctly are:-
i)Double the slashes
f= open(“c:\\temp\\data.txt”,”r”)
ii) Give raw string by prefixing the file-path
string with an ‘r’.
f= open(r“c:\temp\data.txt”,”r”)
File Object/File Handle
 A file object is a reference to a file on disk. It
opens and makes it available for a number of
different tasks.
 File objects are used to read and write data to
a file on disk. The file object is used to obtain a
reference to the file on disk and open it for a
number of different tasks.
File Access Modes
 When Python opens a file, it needs to know
the file-mode in which the file is being opened.
A file mode governs the type of operations
possible in the opened file ie it refers to how
the file will be used once its opened.
Text File Binary File Mode Description Notes
Mode
‘r’ ‘rb’ Read only File must exist already,
otherwise Python raises
I/O Error.
‘w’ ‘wb’ Write only If the file does not exist, file is
created.
If the file exists, it will
truncate the existing data,
and overwrite the file. So this
mode must be used with
caution.
‘a’ ‘ab’ Append File is in write only mode.
If the file exists, the data in
the file is retained and new
data being written will be
appended to the end.
If the file does not exist,
Python will create a new file.
‘r+’ ‘r+b’/ ’rb+’ Read File must exist, otherwise
&Write error is raised.
Both reading and writing
operations can take place.
‘w+’ ‘w+b’/’wb’ Write&Read File is created if does not
exist.
If the file exists, file is
truncated. Past data is lost
Both reading and writing
operations can take place.
‘a+’ ‘a+b’/’ab+’ Write&Read File is created if does not
exist.
If file exists, file’s existing
data is retained, new data is
appended.
Both reading and writing
operations can take place.
Closing Files
 A close function breaks the link of the
file object and the file on the disk.
 After close() no tasks can be
performed on that file through the file
object/file handle.
Syntax
<File handle>.close()
eg:- outfile.close()
Reading and Writing Files

Reading from Files

Sl no Method Syntax Description


1. Read() <fileobject>.read([n Read at most n bytes.if no
]) n is specified,reads the
entire file.Returns the
read bytes in the form of a
string.
2. Readline() <fileobject>.readlin Reads a line of input .If n
e([n]) is specified reads at most
n bytes.Returns the read
bytes in the form of a
string ending with inline
character or returns a
blank string if no more
bytes are left for reading
in the file.
3 Readlines <fileobject>.readlin Reads all lines and returns
() es([n]) them in a list.

Using ‘with’ statement


The with statement is a compact statement
which combines the opening of the file and
processing of the file along with inbuilt
exception handling.
Python’s with statement for files is very
handy when you have two related operations
which you’d like to execute as a pair, with a
block of code in between.
The syntax is:
with open(filename,filemode) as filehandle:
file manipulation statements
eg:- with open(“output.txt”,’w’) as f:
f.write(“Hi there”)
The above with statement will automatically
close the file after the nested block of code.
The advantage of using with statement is that
it is guaranteed to close the file no matter
how the nested block exists.
Even if an exception (a runtime error occurs
before the end of the block , the with
statement will handle it and close the file)
Writing on to Files
Writing Functions
Sl Name Syntax Description
N
o
1 Write() <filehandle>. Writes string str1 to
write(str1) file referenced by file
handle
2 Writelines( <filehandle>. Writes all strings in
) writelines(L) list L as lines to file
referenced by
filehandle.

You might also like