Python Data File Handling XII CS 2022-23 As On 28-10-2022
Python Data File Handling XII CS 2022-23 As On 28-10-2022
❖TYPES OF FILES
❖RELATIVE AND
ABSOLUTE PATHS
INTRODUCTION TO FILES
• Files are used to store data in a storage device permanently.
• File handling provides a mechanism to store the output of a program in
a file and to perform various operations on it.
• The data stored in Secondary Memory storage in a file is given a file name using
which it is accessed.
• The data stored within the file can be read, modified and deleted through
program using different File I/O functions or methods provided by the language.
DFH Poem
➢ INTRODUCTION
Opens a file for both reading and
➢TEXT FILE
▪ File Modes
▪Opening a Text File
r+ writing. The file pointer placed at the
beginning of the file.
PROGRAM CODE
OUTPUT
READING the contents of Friend.txt file
using readline() method
PROGRAM CODE
OUTPUT
PROGRAM CODE
OUTPUT
PROGRAM CODE
OUTPUT
READING the contents of Friend.txt file
using readlines() method
PROGRAM CODE
OUTPUT
Here, readlines() method reads the full file in the form of a LIST.
Every element of the list is the line of the file. For example, the first line of the text file is at List[0] position,
2nd Line at List[1] and so on. Every element of the List is a string ending with a ‘\n’ new line character.
STANDARD FILE STREAMS:
INPUT, OUTPUT AND ERROR STREAMS
The interpreter provides three standard file objects, known as standard input, standard
output, and standard error, which are available in the sys module as sys. stdin,
sys. stdout, and sys. stderr, respectively.
Standard streams in Python are File Objects, which get automatically connected to your program’s
standard device(s) when we start Python. The standard streams available in Python are:
❑ Standard input stream
❑ Standard output stream
❑ Standard error stream
In order to work with I/O stream, we need to import sys module. The methods which are available for
I/O operations in it are:
➢ read() for reading a byte at a time from keyboard
➢ write() for writing data on console, i.e.,monitor
The three standard streams are described as follows:
i. sys.stdin: When a stream reads from standard input.
ii. sys.stdout: Data written to sys.stdout appears on the screen, but can be linked to the standard
input of another program too.
iii. sys.stderr: Error messages are written to sys.stderr. It is similar to sys.stdout as it also prints
directly to the console but with the difference that it also prints exceptions,error messages
along with debugging comments.
WORKING WITH BINARY FILES
BINARY FILE
• Binary Files stores data in the form of BYTES
• Binary Files are in Binary form (0’s and 1’s)
• There is no EOL(End of Line) character in Binary Files
• Example of Binary Files are- image files, Audio files, Video files
• Binary Files don’t require any language translator as they are in Binary Level (0’s and 1’s)
which the computer understands. Hence, any kind of computation and working on
Binary Files is faster.
A Dat file is a data file that contains specific information about the program
used to create it. This file always has the .dat file extension, which is a generic
format that can contain any information – video, audio, PDF, and virtually any
other type of file.
Most of the files that we see in our computer system are called Binary Files.
Examples:
Document Files: .pdf,.doc,.xls etc.
Image Files: .png,.jpg,.bmp etc.
Video files: .mp4,.3gp,.mkv,.avi etc.
Audio Files: .mp3,.wav,.mka,.aac etc.
Database Files: .mdb,.frm,sqlite etc.
Archive Files: .zip,.rar,.iso etc.
Executable Files: .exe,.dll,.class etc.
BINARY FILE MODES
CONTENTS BINARY FILE DESCRIPTION
MODES
➢ INTRODUCTIO
Opens a file for reading only. The file pointer is placed at the
N
➢ TEXT FILE
rb beginning of the file. This is the default mode.
▪ File Opens a file for writing only. Overwrites the file if the file exists. If
Modes
wb the file does not exist, creates a new file for writing.
▪Opening a Opens a file for appending. The file pointer is at the end of the file
Text File
ab if the file exists. That is, the file is in the append mode (write from
▪Closing a File end). If the file does not exist, it creates a new file for writing.
▪Writing/ Opens a file for both reading and writing. The file pointer placed at
appending rb+ or the beginning of the file.
data to a text
file r+b
▪Reading from
Opens a file for both writing and reading. Overwrites the existing
a text file
▪seek and tell
wb+ or file if the file exists. If the file does not exist, creates a new file for
writing and reading.
methods
▪manipulation
w+b
of data in a Opens a file for both appending and reading. The file pointer is at
text file ab+ or the end of the file if the file exists. The file opens in the append
➢ BINARY FILE mode. If the file does not exist, it creates a new file for writing and
➢ CSV FILE a+b reading.
READING and WRITING DATA from/to a BINARY FILE
➢ Suppose, you want to write a Python List or Dictionary to a Binary File and then
intend to read it. For that, you need to use the Python module Pickle.
➢ Pickle module is used for Serialization(Pickling) and Deserialization(Unpickling)
NOTE:
Here, look at the Exception given as EOFError that
means once the pointer started reading the file and
encountered the End of the File. It didn’t stop
automatically rather showed the EOFError
Before READ Operation… let us recap the
concept of exceptions (try and except blocks)
Even if a statement or expression is syntactically correct, it may cause
an error when an attempt is made to execute it.
Errors detected during execution are called exceptions and are not
unconditionally fatal.
Most exceptions are not handled by programs, and result in error
messages. As you have noticed in the previous program.
NOTE:
Here, look at the try block to execute the code and except block to handle the exception.
SEARCHING FROM A BINARY FILE
UPDATING A BINARY FILE
It is a 3 step process:
(i) Locate the record to be updated by
searching for it
(ii) Make changes in the loaded record in
memory( the read record)
(iii)Write back onto the file at the exact
location of old record.
NOTE:
Backward movement of file-pointer is not
possible from the beginning of the file (BOF).
Forward movement of file-pointer is not
possible from the end of file (EOF).
NOTE:
EOL character used in Windows OS is
Carriage Return \r and Line Feed \n \r is treated as one character and \n is treated as one character.
USING WITH STATEMENT
The with statement is a compact statement
which combines the opening of file and
processing of file along with inbuilt exception
handling. The with statement automatically
closes the file too after the execution of the
with block.
SYNTAX:
with open(<filename>,<mode>) as <filehandle>:
# use pickle.load() here inside this with block
# you can perform other file handling operations
UPDATING BINARY FILE RECORD
WORKING WITH CSV FILES
What are CSV files (.CSV files)?
CSV FILES: A comma-separated values (CSV) file is a delimited text file that uses a
comma to separate values. The CSV format refers to a tabular data that has been saved as
plain text where data is separated by commas. The separator character of CSV Files is
known as delimiter. Default and most popular delimiter is comma ,
Other popular delimiters are- tab (\t) , colon (:), pipe (|) and semi-colon (;)
Eg. Prog1.py
csv.writer object
converts the user data into
csv writable form (i.e. in
delimited string form)
ADMNO,NAME,STREAM,MARKS
4132,Sindhu,Science,99.8
csv.reader() returns a reader 5680,Mary,Commerce,96.5
READ from csv.reader() Returns a reader object which loads data from CSV
a CSV File file into an iterable after parsing delimited data
SOME IMPORTANT NOTES:
Q) What is the use of writerow() function in Q) What is the use of writerows()
csv? function in CSV?
Ans) writer() function is used to create a writer.writerows() is used to write
writer object. multiple rows from a buffer that
The writer. writerow() function is then used contains one or more lists at once.
to write single rows to the CSV file.
IMPORTANT NOTE:
csv.reader() and csv.writer() both work with List/Tuple.
** EXTRA KNOWLEDGE
csv.DictReader() and csv.DictWriter() methods work with dictionary.
csv.DictReader and csv.DictWriter take additional argument fieldnames that are used as dictionary keys.
** EXTRA KNOWLEDGE
Reading CSV File Into A Dictionary: To read a CSV file into a dictionary can be done by using DictReader()
class of csv module which works similar to the reader( ) class but creates an object which maps data to
a dictionary.
**HINT: DictReader works by reading the first line of the CSV and using each comma separated value in
this line as a dictionary key. The columns in each subsequent row then behave like dictionary values and
can be accessed with the appropriate key (i.e. fieldname).
Program to READ and WRITE onto a CSV FILE
OUTPUT
• Google.com
• Quora.com
• StackOverflow.com
• Geekforgeeks.com
• Sarthaks.com
• Wikipedia
• XII CS , By Sumita Arora, Dhanpat Rai Publication 2020 Edition
• XII IP , By Sumita Arora, Dhanpat Rai Publication 2020 Edition
Stay safe. Stay aware. Stay healthy. Stay alert.