0% found this document useful (0 votes)
15 views36 pages

Python File Operations and Handling

This document covers Python file operations, detailing how to handle data files for persistent storage. It explains the types of files (text and binary), the steps for file handling (opening, reading/writing, closing), and various file modes. Additionally, it discusses advanced topics such as using the 'with' statement for automatic file closure and random access methods like seek() and tell().

Uploaded by

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

Python File Operations and Handling

This document covers Python file operations, detailing how to handle data files for persistent storage. It explains the types of files (text and binary), the steps for file handling (opening, reading/writing, closing), and various file modes. Additionally, it discusses advanced topics such as using the 'with' statement for automatic file closure and random access methods like seek() and tell().

Uploaded by

mayurkumbhar9945
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Unit -6

Python File Operation


Data File Handling
• We have seen yet only the transient programs. The programs
which run for a short period of time and give some output and
after that their data is disappeared. And when we again run
those programs then we have to use new data.
• This is because the data is entered in primary memory which is
temporary memory and its data is volatile.
• Those programs which are persistent i.e. they are always in
running or run for a long time then their data is stored in
permanent storage (e.g. harddisk) . If the program is closed or
restarted then the data used will be retrieved.
• For this purpose the program should have the capability to read
or write the text files or data files. These files can be saved in
permanent storage.
• The meaning of File I/O (input-output) is to transfer the data from
Primary memory to secondary memory and vice-versa.
(Random Access
Program in RAM Hard
User
Memory)
Disk
Introduction
 FILE HANDLING is a mechanism by which
we can read data of disk files in python
program or write back data from python
program to disk files.

 So far in our python program the standard


input in coming from keyboard an output
is going to monitor i.e. no where data is
stored permanent and entered data is
present as long as program is running
BUT file handling allows us to store data
entered through python program
permanently in disk file and later on we
can read back the data.
Why the Files are

because
used?
The data stored with in a file is known as persistent data

this data is permanently stored in the system.


• Python provides reading and writing capability of data files.
• We save the data in the files for further use.
• As you save your data in files using word, excel etc. same
thing we
can do with python.
• “A File is a collection of characters in which we can
perform read and write functions. And also we can save it
Write to file
in secondary storage.” (Save)
Python External
Program File
(Secondar
y
Read from Storage)
file
(Load)
File Types
File are of two types –
1. Text File: A text file is sequence of line and line is the
sequence of characters and this file is saved in a
permanent storage device. Although in python
default character coding is ASCII but by using
constant ‘U’ this can be converted into UNICODE. In
Text File each line terminates with a special
character which is EOL (End Of Line). These are in
human readable form and these can be created
using any text editor.
2. Binary File: Binary files are used to store binary data
such as images, videos audio etc. Generally
numbers are stored in binary files. In binary file,
there is no delimiter to end a line. Since they are
directly in the form of binary hence there is no need
to translate them. That’s why these files are easy and
fast in working.
Steps in Data File
Handling
1. OPENING FILE
 We should first open the file for read or
write by specifying the name of file and
mode.
2. PERFORMING READ/WRITE
 Once the file is opened now we can either
read or write for which file is opened using
various functions available
3. CLOSING FILE
 After performing operation we must close
the file and release the file for other
application to use it.
Data File
Following main operations can be done on
files - Operations
1. Opening a file
2. [Link]
READ operations
2. WRITE etc.
3. Closing The
File
Open Process Close
File Data File
Beside above operations there are some more operations can be
done on
files.-
• Creating of Files
• Traversing of Data
• Appending Data into file.
• Inserting Data into File.
• Deleting Data from File.
• Copying of File.
• Updating Data into File.
Opening & Closing
• We need a Files
file variable or file handle to work with files in
Python.
• This file object can be created by using open( ) function
or file( ) function.
• Open( ) function creates a file object, which is used later
to access
the file using the functions related to file manipulation.
• Itssyntax is following -
<file_object>=open(<file_name>,<access_mode>)
OR
Python External
file_object = open(filename )
Program File
(Seconda
• File accessing modes - ry
– write(w): to write to the file Storage)
– read(r): To read the file Read from
– append(a): to Write at the end of file
file. (Load)
** default mode is
Closing
file
 As reference of disk file is stored in
file handle so to close we must call
the close() function through the file
handle and release the file.

[Link]()

Note: open function is built-in function


used standalone while close() must be
called through file handle
Opening & Closing
Files. . . Opened the File
Here the point is that the file “[Link]” which is used here is pre
built and stored in the same folder where Python is installed.

The file is closed.


The file is closed.

A program describing the functions of file handling.


Output
File
Mode Description
r To read the file which is Modes
already existing.
r+ To Read and write but the file pointer will be at the beginning of the file.
w Only writing mode, if file is existing the old file will be overwritten else the
new file will be created.
w+ Write and read

a Append mode. The file pointer will be at the end of the file.
a+ Appending and reading if the file is existing then file pointer will be at the
end of the file else new file will be created for reading and writing.
rb Read Only in binary format.
rb+ To Read and write binary file. But the file pointer will be at the beginning
of the file.
wb Binary file only in writing mode, if file is existing the old file will be
overwritten else the new file will be created.
wb+ Binary file only in reading and writing mode, if file is existing the old file will
be
overwritten else the new file will be created.
ab Append mode in binary file. The file pointer will be at the end of the file.
ab+ Appending and reading in binary file if the file is existing then file pointer
will be at the end of the file else new file will be created for reading and
Reading from
File
 To read from file python provide many
functions like :
 [Link]([n]) : reads and
return n bytes, if n is not specified it
reads entire file.
 [Link]([n]) : reads a
line of input. If n is specified reads at
most n bytes. Read bytes in the form of
string ending with line character or
blank string if no more bytes are left for
reading.
 [Link](): reads all
Reading a
File
A Program to read
“[Link]” File.

Output

[Link] file was


created using
notepad.|
Reading a
File . . . Reading first 10
characters from the
file “[Link]”

Output

1. We can also use readline( ) function which can read one


line at a time from the file.
2. Same readlines( ) function is used to read many lines.
Example: readline()
SAMPLE
FILE
Example-3:
FILEreadline()
SAMPLE

HAVE YOU NOTICED THE DIFFERENCE IN OUTPUT FROM


PREVIOUS OUPUT?
Example-: reading line by line using readline()
SAMPLE
FILE
Example-: readlines()
SAMPLE
FILE
Example: counting size of file in bytes and Number of Lines in
File
SAMPLE
FILE
Writing to a
• We can write characters into file by using following two methods
- File
1. write (string)
2. writelines (sequence of lines)
• write( ) : it takes a sting as argument and adds to the file. We
have to use ‘\n’ in string for end of line character .
• writelines ( )
: if we want to write list, tuple into the file
then we use writelines ( ) function.
A program to write in
“[Link]”

This “[Link]” is created using above


program.

Output
write() using “w”
mode

If we want to add new data without


overwriting the previous content then we
should write using “a” mode i.e. append
mode.
write() using “a”
mode

New content is
added after
previous
content
Writing to a
File. . .

A Program to use writelines()


function

Output

“[Link]” File is
created using the
above program.
“with”
statement
 Python’s “with” statement for file
handling is very handy when you have
two related operations which you
would like to execute as a pair, with a
block of code in between:
with open(filename[, mode]) as
filehandle:
file_manipulation_statemen
t
 The advantage of “with” is it will
automatically close the file after
nested block of code. It guarantees
Exampl
e
Writing to a
[Link].
file is opened using “with”.

Output

“[Link]” File is
created using the
above program.
Example: Writing String as a record to file
To copy the content of one file to another file
Appending in a
• Append means adding something new to existing file.
File
• ‘a’ mode is used to accomplish this task. It means opening
a file in write mode and if file is existing then adding data
to the end of the file.
A program to append
into a file “[Link]”

Output

A new data is appended into


[Link] by above program.
Writing User Input to the
File.
Taking data
the user from
and writing
data this the
to file
“Stud [Link]”.
Student File is
e created by using
the above
Output program.
Operations in Binary

File.
If we want to write structure such as list, dictionary etc and
also we want to read it then we have to use a module in
python known as pickle.
• Pickling means converting structure into byte stream
before writing the data into file.
• And when we read a file then a opposite operation
is to be done means unpickling.
• Pickle module has two methods –
• dump( ) to write the object in file which is loaded in binary
mode.
Syntax :dump(object_to_write, filehandle)

• load( ) dumped data can be read from file using load()


i.e. it is used to read object from pickle file.
Syntax:object = load(filehandle)
Operations in Binary File

To write Binary file use of dump( ) function


Operations in Binary
• To read Binary file use of load ( )
function -
File
RANDOM ACCESS METHODS

• All reading and writing functions discussed


till now, work sequentially in the file.

• To access the contents of file randomly –


following methods.

1. seek method

2. tell method

34
RANDOM ACCESS METHODS
Seek() method :
• seek()method can be used to position the file object
at particular place in the file.
syntax is :
[Link](offset [, from_what])
• Here offset is used to calculate the position of
fileobject in the file in bytes. Offset is added to
from_what (reference point) to get the position.
• Value reference point:
0 -beginning of the
file 1 -current
position of file 2 -end
of file
• Default value of
from_what is 0, i.e. 23
RANDOM ACCESS METHODS
tell method
• tell() method returns an integer giving the current position
of object in the file.
• The integer returned specifies the number of bytes from
the beginning of the file till the current position of file object.
Syntax:
[Link]()
• tell() method returns an integer and assigned to pos
variable. It is
the current position from the beginning of file.

36

You might also like