0% found this document useful (0 votes)
28 views48 pages

File Handling

Imp for SSC

Uploaded by

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

File Handling

Imp for SSC

Uploaded by

aashishdutta398
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

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 and
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

Maninder Singh 1
DATA FILES
• The data files are the files that store data pertaining to a specific
application, for later use.

• The data files can be stored in two ways –

• Text File

• Binary File

Maninder Singh 2
Text File
• Text file stores information in ASCII OR UNICODE character. In text file
everything will be stored as a character for example if data is "computer"
then it will take 8 bytes and if the data is floating value like 11237.9876 it
will take 10 bytes.

• In text file each line is terminated by special character called EOL. In text
file some translation takes place when this EOL character is read or
written. In python EOL is ‘\n’ or ‘\r’ or combination of both

Maninder Singh 3
Binary files
• It stores the information in the same format as in the memory i.e.
data is stored according to its data type so no translation occurs.

• In binary file there is no delimiter for a new line

• Binary files are faster and easier for a program to read and write than
text files.

• Data in binary files cannot be directly read, it can be read only


through python program for the same.

Maninder Singh 4
Steps in Data File Handling
• OPENING FILE
• We should first open the file for read or write by specifying the name of file and mode.

• PERFORMING READ/WRITE
• Once the file is opened now we can either read or write for which file is opened using
various functions available

• CLOSING FILE
• After performing operation we must close the file and release the file for other
application to use it,

Maninder Singh 5
Opening File
File can be opened for either – read, write, append.

It is done using open() function.

SYNTAX:

file_object = open(filename)

Or

file_object = open(filename,mode)

** default mode is “read”

Maninder Singh 6
Opening File
myfile = open(“story.txt”)

here disk file “story.txt” is loaded in memory and its reference is linked
to “myfile” object, now python program will access “story.txt” through
“myfile” object.

• here “story.txt” is present in the same folder where .py file is stored
otherwise if disk file to work is in another folder we have to give full
path.

Maninder Singh 7
Opening File
myfile = open(“article.txt”,”r”)

• Here “r” is for read (although it is by default, other options are “w” for write, “a” for append)

myfile = open(“d:\\mydata\\poem.txt”,”r”)

• Here we are accessing “poem.txt” file stored in separate location i.e. d:\mydata folder.

• At the time of giving path of file we must use double backslash(\\) in place of single backslash
because in python single slash is used for escape character and it may cause problem like if
the folder name is “nitin” and we provide path as d:\nitin\poem.txt then in \nitin “\n” will
become escape character for new line, SO ALWAYS USE DOUBLE BACKSLASH IN PATH

Maninder Singh 8
Opening File
myfile = open(“d:\\mydata\\poem.txt”,”r”)

Another solution of double backslash is using “r” before the path, making
the string as raw string i.e. no special meaning attached to any character as:

myfile = open(r“d:\mydata\poem.txt”,”r”)

Maninder Singh 9
File Object/File Handle
File objects are used to read and write data to a file on disk.
A file objects is reference to a file on disk.
It opens and make it available for a number of different tasks.
myfile = open(r“d:\mydata\poem.txt”,”r”)
In the above example “myfile” is the file object or file handle or file
pointer holding the reference of disk file. In python we will access and
manipulate the disk file through this file handle only.

Maninder Singh 10
File Access Mode
Text
File Binary File
Mode Mode Description Notes
‘r’ ‘rb’ Read only File must exists, otherwise Python raises I/O errors
If file not exists, file is created
If file exists, python will truncate existing data and overwrite the
‘w’ ‘wb’ Write only file.
File is in write mode only, new data will be added to the end of
‘a’ ‘ab’ Append existing data i.e. no overwriting. If file not exists it is created
File must exists otherwise error is raised Both reading and writing
‘r+’ ‘r+b’ or ‘rb+’ Read and write can take place
File is created if not exists, if exists data will be truncated, both
w+ ‘w+b’ or ‘wb+’ Write and read read and write allowed
Same as above but previous content will be retained and both
‘a+’ ‘a+b’ or ‘ab+’ Write and read read and write.

Maninder Singh 11
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.
The close() function breaks the link of file-object and the file on the disk.
After close(), no tasks can be performed on that file through the file-object
or file-handle.
myfile.close()
Note: open function is built-in function used standalone while close() must
be called through file handle

Maninder Singh 12
Reading from File
• To read from file python provide many functions like :
• Filehandle.read([n]) : reads and return n bytes, if n is not specified it
reads entire file.
• Filehandle.readline([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.
• Filehandle.readlines(): reads all lines and returns them in a list

Maninder Singh 13
E x a m p l e : read()

Maninder Singh 14
E x a m p l e : read()

Maninder Singh 15
E x a m p l e : readline()

Maninder Singh 16
E x a m p l e : readlines()

Maninder Singh 17
E x a m p l e : read()

Maninder Singh 18
E x a m p l e : readline ()

Maninder Singh 19
E x a m p l e : reading line by line using readline()

Maninder Singh 20
E x a m p l e : reading line by line using for loop

Maninder Singh 21
E x a m p l e : readlines()

Maninder Singh 22
Example : counting size of files in bytes

Maninder Singh 23
Example : counting no. of lines from text file

Maninder Singh 24
Example : Calculating size of text file with and
without EOL and blank lines

Maninder Singh 25
Writing onto files
• After read operation, let us take an example of how to write data in disk
files.
• Python provides functions:
• write ()
• writelines()
• The above functions are called by the filehandle to write desired content.
Name Syntax Description
Writes string str1 to file referenced by
write() Filehandle.write(str1)
filehandle
Writes all string in List L as lines to file
writelines() Filehandle.writelines(L)
referenced by filehandle.

Maninder Singh 26
Example : write() using “w” mode

Maninder Singh 27
WAP to get roll, name and marks of a student
of a class and store these details in a file.

Maninder Singh 28
Example : write() using “w” mode

Lets run the


same program
again

Maninder Singh 29
Example : write() using “w” mode

Now we can observe that while writing data to file using


“w” mode the previous content of existing file will be
overwritten and new content will be saved.

If we want to add new data without overwriting the


previous content then we should write using “a” mode
i.e. append mode.

Maninder Singh 30
Example : write() using “a” mode

Maninder Singh 31
Example : using writelines()

Maninder Singh 32
Example : Writing String as a record to file

Maninder Singh 33
Example : Writing String as a record to file

Maninder Singh 34
Example: To copy the content of one file to another file

Maninder Singh 35
flush() function
• When we write any data to file, python hold everything in buffer
(temporary memory) and pushes it onto actual file later. If you want
to force Python to write the content of buffer onto storage, you can
use flush() function.

• Python automatically flushes the files when closing them i.e. it will be
implicitly called by the close(), BUT if you want to flush before closing
any file you can use flush()

Maninder Singh 36
Example: working of flush()
Without flush()

Nothing is
When you run the above code, program will stopped in the file
at “Press any key”, for time being don’t press any key temp.txt
and go to folder where file “temp.txt” is created an
open it to see what is in the file till now

N O W P R E S S A N Y K E Y ….

Now content is stored,


because of close()
function contents are
flushed and pushed in file
Maninder Singh 37
Example: working of flush()
With flush()

All contents
before flush()
When you run the above code, program will stopped at are present in
“Press any key”, for time being don’t press any key and file
go to folder where file “temp.txt” is created an open it
to see what is in the file till now

N O W P R E S S A N Y K E Y ….

Rest of the content is


written because of
close(), contents are
flushed and pushed in file.
Maninder Singh 38
Removing whitespaces after reading from file
• read() and readline() reads data from file and return it in the form of
string and readlines() returns data in the form of list.
• All these read function also read leading and trailing whitespaces,
new line characters. If you want to remove these characters you can
use functions
• strip() : removes the given character from both ends.
• lstrip(): removes given character from left end
• rstrip(): removes given character from right end

Maninder Singh 39
Example: strip(), lstrip(), rstrip()

Maninder Singh 40
File Pointer
• Every file maintains a file pointer which tells the current position in the
file where reading and writing operation will take.

• When we perform any read/write operation two things happens:


• The operation at the current position of file pointer

• File pointer advances by the specified number of bytes.

Maninder Singh 41
Example : File Pointer
myfile = open(“ipl.txt”,”r”) ch = myfile.read(1)

File pointer will be by ch will store first character i.e. first


default at first position character is consumed, and file
i.e. first character pointer will move to next character

Maninder Singh 42
File Modes and Opening position of file pointer
FILE MODE OPENING POSITION

r, r+, rb, rb+, r+b Beginning of file


Beginning of file (overwrites the file if
w, w+, wb, wb+, w+b
file already exists)
At the end of file if file exists
a, ab, a+, ab+, a+b
otherwise creates a new file

Maninder Singh 43
Standard INPUT, OUTPUT and ERROR STREAM
• Standard Input : Keyboard
• Standard Output : Monitor
• Standard error : Monitor
• Standard Input devices(stdin) reads from keyboard
• Standard output devices(stdout) display output on monitor
• Standard error devices(stderr) same as stdout but normally for errors
only.

Maninder Singh 44
Standard INPUT, OUTPUT and ERROR STREAM
• The standard devices are implemented as files called standard
streams in Python and we can use them by using sys module.
• After importing sys module we can use standard streams stdin,
stdout, stderr

Maninder Singh 45
“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_statement
• The advantage of “with” is it will automatically close the file after
nested block of code. It guarantees to close the file how nested block
exits even if any run time error occurs

Maninder Singh 46
“with” statement

Maninder Singh 47
“with” statement

Maninder Singh 48

You might also like