CS12 FileHandlingPythonPart2
CS12 FileHandlingPythonPart2
PART – II
(Based on Binary Files)
1
Binary File ? … stores information in the same format as it is held in the memory
Pickle module can be used to store and retrieve any object (integer, float,
strings, lists, dictionary etc. ) in a binary file.
Pickle module is thus used for serializing and de-serializing Python objects.
Serialization (Pickling) refers to the process of converting an object in memory to a byte stream that can be
stored on disk.
Deserialization (Unpickling) converts the byte stream (generated through pickling) back into python object.
2
Steps to use Pickle module
1. Import the module file_object = open(filename , access_mode )
3. Use methods pickle.dump() / pickle.load() to write / read from and from binary files.
[ {'rollno': 11,
'name': 'aa',
'stream':
'science',
'percent': 97.0} ]
6
APPEND TO A BINARY FILE
[ {},{}…]
[ {'rollno': 22,
'name': ‘bb',
'stream':
‘commerce’
'percent': 95} ]
7
DISPLAY FROM A BINARY FILE
L is a list of
dictionary items
[{},{},{}]
OR
Output
Output
x
x
x
8
SEARCH & DISPLAY FROM A BINARY FILE
science
Output
9
UPDATE A BINARY FILE
33
95
33
95 L
95
10
DELETE FROM A BINARY FILE
22
22
L
0
1
2
11
12
STANDARD STREAMS
Standard streams* are file objects, which get automatically connected to program's standard device(s), when
we start python.
Programs make output to "stdout" and "stderr" . By default, both are written to the screen.
Programs take input from “stdin”. By default, input is taken from the keyboard.
In order to work with standard I/O stream, we need to import sys module.
i.e. Python uses sys.stdin , sys.stdout and sys.stderr streams
13
14
Example of using sys.stdin to read
INPUT BUFFER
hello world\n
display’s only first 5 characters
INPUT BUFFER
world\nis everyone ok?\n
15
Difference between input( ) and readline( )
input( ) readline( )
The input takes input from the user but The readline() also takes input from the
does not read escape character (Enter key user but also reads the escape character (
or \n character ) nter key or \n character )
It has a prompt that represents the default Readline has a parameter named size,
value before the user input. Which is a non-negative number, it actually
defines the bytes to be read.
Example: Example:
S = input(‘Enter a value: ‘) import sys
S = sys.stdin.readline( )
16
Using sys.stdout and sys.stderr to write
Method Meaning Example
sys.stdout.write( s ) It writes a single string to the standard
sys.stderr.write( s ) output buffer.
Output:
Output:
17
Example of using sys.stdin, sys.stdout and sys.stderr
strive for success
18
Difference between print( ) and write( ) : print() displays output on screen and puts a \n after the output.
Write() does not put \n after displaying output so subsequent outputs from print would appear in the same line.
File Path path + name of the file
Syntax of open() :
file_object = open(filename [, access_mode] )
If no path is included then, the file is assumed to be in the current working directory (CWD)
file = open(‘story.txt’) C:
Users
To open a file from other than CWD, path along name of file has to specified
Python allows using both forward slash "/" and backslash “\” in the file path. abc
Desktop
1st method: file = open( 'C:/Users/abc/Desktop/story.txt‘)
Story.txt
2nd method: file = open('C:\\Users\\abc\\Desktop\\story.txt‘)
If using backslash, because it is a special character in Python, you must remember to escape it’s every instance
A directory refers to a folder on a computer. Directories are hierarchical which means that they can exist within
other folders as well as have folders exist within them.
What is the Home Directory?
The home directory on a computer is a directory defined by your operating system. The home directory is the
primary directory for your user account on your computer. Your files are by default stored in your home directory.
On Windows, the home directory is typically C:\Users\your-username
On Mac and Linux, the home directory is typically /home/your-username
CWD on my system
20
Absolute Paths
An absolute path is a path that contains the entire path to the file or directory that you need to access. This path
will begin at the home directory of your computer and will end with the file or directory that you wish to access.
Absolute paths ensure that Python can find the exact file on your computer.
file = open( 'C:/Users/abc/Desktop/story.txt‘)
An absolute path, always begins with the root folder (C: or D: etc on Windows)
Relative Paths
A relative file path is relative to the program’s current working directory. It interpreted from the perspective your
current working directory.
There are also the dot (.) and dot-dot (..) folders.
These are not real folders but special names that can be used in a path.
A single period (“dot”) for a folder name is shorthand for “this directory.”
Two periods (“dot-dot”) means “the parent folder.”
21
ABSOLUTE VS. RELATIVE PATHS
23
fileobject attributes
Some useful attributes of fileobject
1. file.closed returns True if file is closed
2. file.mode returns the mode, with which file was opened.
3. file.name returns name of the file associated with file object while opening the file.
Example:
Note: We have already covered various methods of fileobject like open() , close() , read() , readline() ,
readlines() , write() , writelines()
24
Next > File Handling Part -3 (Based on CSV Files)
25