The document discusses file handling in Python. It covers opening and closing files, reading from and writing to text files, and some basic file operations like reading line by line. The key points are:
1. File handling allows permanent storage of data by opening, reading, and writing to files.
2. The open() function is used to open a file and return a file object, specifying the file name and mode.
3. Common file modes are 'r' for reading, 'w' for writing and truncating, 'a' for appending.
4. Methods like read(), readline(), readlines() are used to read a file contents, while write() writes to files.
.
Class-XII Computer Science(083)
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
Computational Thinking and Programming - 2
File Handling
Text File
S K Mahto, PGT (Computer Science)
J.N.V East Medinipur WB
2.
File Handling
Learning Outcomes
●Apply the concept of file
handling.
● Understand the
importance of data file
for permanent storage of
data.
● Understand how
standard Input / Output
function work.
● Open and close a file .
● Read and write data in
file
● Write programs that
manipulate data file(s).
Syllabus
• File handling : Need for a data file, Types of file: Text files, Binary files
and CSV (Comma separated values) files.
• Text File : Basic operations on a text file: Open (filename – absolute or
relative path, mode) / Close a text file, Reading and Manipulation of
data from a text file, Appending data into a text file, standard input /
output and error streams, relative and absolute paths.
• Binary File : Basic operations on a binary file: Open (filename –
absolute or relative path, mode) / Close a binary file, Pickle Module –
methods load and dump; Read, Write/Create, Search, Append and
Update operations in a binary file.
• CSV File : Import csv module, functions – Open / Close a csv file, Read
from a csv file and Write into a csv file using csv.reader ( ) and
csv.writerow( ).
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
3.
File Handling
Need fora data file
● In all the programs we have made so far when program is closed all the data is
lost, but what if we want to keep the data to use later? This is where file handling
comes in.
● Python allows us to read data in from and save data to external text files.
Need -
● To Store data in organized manner
● To store data permanently
● To access data faster
● To Search data faster
● To easily modify data later on
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
4.
File Handling
Types offile
● File - A file (i.e. data file) is a named place on the disk where a
sequence of related data is stored.
● A file in itself is a bunch of bytes stored on some storage device like
Hard-disk, Removable disk etc.
● 1. Text files
● 2. Binary files
● 3. CSV files
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
5.
File Handling
Text file
●A text file is usually considered as sequence of lines.
● Line is a sequence of characters (ASCII or UNICODE), stored on
permanent storage media.
● The default character coding in python is ASCII each line is terminated
by a special character, known as End of Line (EOL).
● At the lowest level, text file will be collection of bytes.
● Text files are stored in human readable form and they can also be
created using any text editor.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
6.
File Handling
Binary File
●A binary file stores the data in the same way as stored in the memory.
i.e. the file content that is returned us is raw. (with no translation or no
specific encoding).
● In binary file there is no delimiter for a line.
● No translation occur in binary files, as a result, binary files are faster
and easier for a program to read and writer than a text files.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
7.
File Handling
CSV File
●A CSV file is a human readable text file where each line has a number of
fields, separated by commas or some other delimiter.
● Python has a vast library of modules that are included with its
distribution. The csv module gives the Python programmer the ability to
parse CSV (Comma Separated Values) files.
● The CSV format has no standard, but they are similar enough that the
csv module will be able to read the vast majority of CSV files.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
8.
File Handling
Opening afile – open() function
● To handle data files in python, we need to have a file object.
● File objects are used to read and write data to a file on disk.
● Before we can read or write a file, we have to open it using
Python's built-in open() function.
● open() function creates a file object.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
9.
File Handling
Opening afile – open() function
Syntax - file-object = open(file-name [, access-mode][, buffering])
default file mode is – read mode
● The file-name argument is a string value that contains the name of the file that
you want to access.
● The access-mode determines the mode in which the file has to be opened, i.e.,
read, write, append, etc.
● If the buffering value is set to 0, no buffering takes place. If the buffering value
is 1, line buffering is performed while accessing a file.
● If we specify the buffering value as an integer greater than 1, then buffering
action is performed with the indicated buffer size. If negative, the buffer size is
the system default(default behavior).
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
10.
File Handling
Basic operationson a data file
● Naming a file
● Opening a file
● Reading data from the file
● Writing data in the file
● Closing a file
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
Using these basic operations we can
process file in many ways-
• Creating file
• Traversing a file for displaying the data on
Screen
• Appending data in file
• Inserting data in file
• Deleting data from file
• Create a copy of file
• Updating data in the file
11.
File Handling
Opening afile – File Access Modes
Text file
Mode
Binary file
Mode
Description Notes
‘r’ ‘rb’ read only File must exist already.
‘w’ ‘wb’ write only If file does not exist, file is created.
If file exist, it truncate existing data and overwrite
in the file.
‘a’ ‘ab’ append File is in write only mode.
If the file exist, the data in the file is retained and
new data being written will be appended to the end.
If file does not exist, It will create a new file.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
12.
File Handling
Opening afile – File Access Modes..
Text file
Mode
Binary file
Mode
Description Notes
‘r+’ ‘rb+’ read &
write
File must exist otherwise error is raised.
Both reading & writing operation can take place.
‘w+’ ‘wb+’ write &
read
File is created if file does not exist.
If file exist, file is truncated (past data is lost)
Both reading and writing operation can take place.
‘a+’ ‘ab+’ write &
read
File is created if file does not exist.
If file exist, file’s existing data is retained; new data is appended.
Both reading and writing operation can take place.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
13.
File Handling
Opening afile – The file objects attributes
Once a file is opened and we have one file object, we can get various
information related to that file.
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.
file.softspace Returns false if space explicitly required with print ,
true otherwise.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
14.
File Handling
Opening afile – Example
f = open(‘sanjay.txt’, ‘r’)
● f is a file variable that links the physical file.
● First argument to open is file name
can give a full path
● Second argument is mode for opening file
Read ‘r’ : opens a file for reading only
Write ‘w’ : creates and empty file to write to
Append ‘a’ : appends to an existing file
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
15.
File Handling
Opening afile – Example
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
16.
File Handling
Closing afile – close() function
● A close() function breaks the link of file-object and the file on the disk.
● The close() method of a file object flushes any unwritten information and closes
the file object, after which no more writing/ reading can be done.
● Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method to close
a file.
Syntax – fileobject.close()
Example – f.close()
● f.flush() Manually forces write to disk
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
17.
File Handling
Reading fromfiles
read() - Reads entire file into name as a single string.
Syntax : fileObject.read([count])
Here, passed parameter is the number of
bytes to be read from the opened file.
Example : contents = f.read()
readline() – Reads one line into name , lines ends with ‘n’
contents = f.readline()
readlines()- Reads entire file as list of strings
Each string is one line, ending with ‘n’
contents = f.readlines()
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
18.
File Handling
Reading fromfiles
Text file – sanjay.txt
Path of file
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
19.
File Handling
Reading fromfiles
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
20.
File Handling
Reading fromfiles
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
21.
File Handling
Reading accordingto size
f.read(2) – will read 2 characters / bytes
f.read(4) – will read 4 characters / bytes
….. and so on.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
22.
File Handling
Reading fromfiles
File Pointer
● All read and write operations in a file begins at the file pointer.
● A file pointer is simply a marker which keeps track of the number
of bytes read or written in a file.
● This pointer automatically moves after every read or write
operation.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
23.
File Handling
Writing ontofiles
● f.write(s)
Write string s to a file
Return no. of characters written
Include ‘n’ explicitly to go to a new line
● f.writelines(s)
Write a list of lines s to file
Must include ‘n’ explicitly for each string
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
24.
File Handling
Writing ontofiles
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
25.
File Handling
Writing ontofiles
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
26.
File Handling
Writing ontofiles – appending data
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
27.
File Handling
Writing ontofiles
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
28.
File Handling
Program-1
All thecontents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
29.
File Handling
Program-2
All thecontents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
30.
File Handling
Program-3
All thecontents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
31.
File Handling
Programs
WAP toread a entire text file
WAP to count no. of lines
WAP to count the frequency of a word
WAP to find the size of plain text file
Etc
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
32.
File Handling
Random AccessMethods
● All reading and writing functions discussed till now, work sequentially in
the file. To access the contents of file randomly –following methods are
use.
● seek() method
● tell() method
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
33.
File Handling
Random AccessMethods
● seek() method : can be used to position the file object at particular place
in the file.
● Syntax
fileobject.seek(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.
continue….
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
34.
File Handling
Random AccessMethods
● 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. beginning of the file.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
35.
File Handling
Random AccessMethods - Example
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
36.
File Handling
Random AccessMethods
● 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
fileobject.tell()
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
37.
File Handling
Random AccessMethods - example
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
38.
File Handling
Binary File
●A binary file stores the data in the same way as stored in the memory.
i.e. the file content that is returned us is raw. (with no translation or no
specific encoding).
● In binary file there is no delimiter for a line.
● No translation occur in binary files, as a result, binary files are faster
and easier for a program to read and writer than a text files.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
39.
File Handling
Binary File
●The open() function opens a file in text format by default. To open a file
in binary format, add 'b' to the mode parameter. Hence the "rb" mode
opens the file in binary format for reading, while the "wb" mode opens
the file in binary format for writing. Unlike text mode files, binary files
are not human readable. When opened using any text editor, the data is
unrecognizable.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
40.
File Handling
Binary File- Example
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
The Code stores a list of numbers in a binary file. The list is
first converted in a byte array before writing. The built-in
function bytearray() returns a byte representation of the
object.
To read the above binary file, the output of
the read() method is casted to a list using
the list() function.
41.
File Handling
Binary File- Example
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
Method Description
file.close() Closes the file.
file.flush() Flushes the internal buffer.
next(file) Returns the next line from the file each time it is called.
file.read([size]) Reads at a specified number of bytes from the file.
file.readline() Reads one entire line from the file.
file.readlines() Reads until EOF and returns a list containing the lines.
file.seek(offset, from) Sets the file's current position.
file.tell() Returns the file's current position
file.write(str) Writes a string to the file. There is no return value.
42.
File Handling
Binary File– pickle module [ import pickle ]
● Python pickle module is used for serializing and de-serializing python object
structures.
● The process to converts any kind of python objects (list, dict, etc.) into byte
streams (0s and 1s) is called pickling or serialization or flattening or marshalling.
● We can converts the byte stream (generated through pickling) back into python
objects by a process called as unpickling.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
43.
File Handling
Why pickle?
●The pickle module provides the following functions to make the pickling process-
○ pickle.dump(obj, file)
○ Write a pickled representation of obj to the open file object file
○ file must have a write() method that accepts a single string argument. It can
thus be a file object opened for writing.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
44.
File Handling
○ pickle.load(file)
○Read a string from the open file object file and interpret it as a pickle data
stream, reconstructing and returning the original object hierarchy
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
45.
File Handling
Pickle Exceptions
Beloware some of the common exceptions raised while dealing with pickle module −
● Pickle.PicklingError: If the pickle object doesn’t support pickling, this exception is
raised.
● Pickle.UnpicklingError: In case the file contains bad or corrupted data.
● EOFError: In case the end of file is detected, this exception is raised.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
try:
print(x)
except:
print("An exception occurred")
x=6
try:
print(x)
except:
print("An exception occurred")
46.
File Handling
Menu drivenprogram to Write/Create, Search, Append, Delete and Update operations in a binary file.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
47.
File Handling
Menu drivenprogram to Write/Create, Search, Append, Delete and Update operations in a binary file.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
48.
File Handling
Menu drivenprogram to Write/Create, Search, Append, Delete and Update operations in a binary file.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
49.
File Handling
Menu drivenprogram to Write/Create, Search, Append, Delete and Update operations in a binary file.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
50.
File Handling
Menu drivenprogram to Write/Create, Search, Append, Delete and Update operations in a binary file.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.
51.
File Handling
Menu drivenprogram to Write/Create, Search, Append, Delete and Update operations in a binary file.
All the contents used as part of the slides are either self created or from the public domain or textbooks for Class XII.
This presentation is only used for leaning purpose only. Programs used in this presentation are based on Python 3.8.0.