File Handling in Python
File Handling in Python
✔ INTRODUCTION
✔ DATA FILES
✔ OPENING AND CLOSING FILES
✔ READING AND WRITING FILES
✔ STANDARD INPUT, OUTPUT AND ERROR
STREAMS
Introductio
n
▪ 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
DATA
FILES
▪ It contains data pertaining to a specific
application, for later use. The data files can
be stored in two ways –
▪ Text File
▪ Binary File
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 like 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
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.
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,
Opening
File
▪ File can be opened for either – read, write,
append.
SYNTAX:
file_object = open(filename)
Or
file_object = open(filename,mode)
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
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”)
File
Handle
myfile = open(r“d:\mydata\poem.txt”,”r”)
Mode
‘r’ ‘rb’ Read only File must exists, otherwise Python raises
I/O errors
‘w’ ‘wb’ Write only If file not exists, file is created
If file exists, python will truncate existing
data and overwrite the file.
‘a’ ‘ab’ Append File is in write mode only, new data will
be added to the end of existing data i.e.
no overwriting. If file not exists it is
created
‘r+’ ‘r+b’ or ‘rb+’ Read and write File must exists otherwise error is raised
Both reading and writing can take place
w+ ‘w+b’ or ‘wb+’ Write and read File is created if not exists, if exists data
will be truncated, both read and write
allowed
‘a+’ ‘a+b’ or ‘ab+’ Write and read Same as above but previous content will
VINOD K UMAR VERMA, PGT(CS), KV OEF KANPUR &
SAC HIN BHARDWAJ, PGT(CS) , KV NO.1 TEZPUR
be retained and both read and write.
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.
myfile.close()
Questions
…
Writing onto
▪ After read operation, let us take an
files
example of how to write data in disk files.
Python provides functions:
write ()
writelines()
▪ The above functions are called by the file
handle to write desired content.
Name Syntax Description
write() Filehandle.write(str1) Writes string str1 to file referenced
by filehandle
Writelines() Filehandle.writelines(L) Writes all string in List L as lines to
file referenced by filehandle.
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
Example-1 write() using “w”
: mode
for more updates visit: www.python4csip.com
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.
New content is
added after
previous content
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
for more updates visit: www.python4csip.com
Example-3 using
: writelines()
When you run the above code, program will stopped at “Press any key”, for
time being don’t press any key and go to folder where file “temp.txt” is
created an open it to see what is in the file till now
NOW PRESS ANY KEY….
pushed in file
Example: working of All contents
before
flush()
With flush()
flush() are
present in
file
When you run the above code, program will stopped at “Press any key”, for
time being don’t press any key and go to folder where file “temp.txt” is
created an open it to see what is in the file till now
NOW PRESS ANY KEY….
pushed in file.
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
Example: strip(),
lstrip(), rstrip()
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.
Exampl
e
myfile = open(“ipl.txt”,”r”)
ch = myfile.read(1)
ch will store first character i.e. first character is consumed, and file pointer will
move to next character
File Modes and Opening
position of file pointer
FILE MODE OPENING POSITION
r, r+, rb, rb+, r+b Beginning of file
w, w+, wb, wb+, w+b Beginning of file (overwrites the file if
file already exists
a, ab, a+, ab+, a+b At the end of file if file exists otherwise
creates a new file
Standard INPUT, OUTPUT and ERROR
STREAM
◾
loaded in binary mode
Syntax : dump(object_to_write, filehandle)
◾
load() i.e. it is used to read object from pickle file.
Syntax: object = load(filehandle)
Example:
dump()
SALES IT HR PROD
FOLDE R FOLDE R FOLDE R FOLDE R
SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER
.\2019\SHEET.XLS
Relative
Current
addressing working
C:\
directory
DRIVE
SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER
..\NOIDA\SEC_8.XLS
Getting name of current
working directory
import os
pwd = os.getcwd()
print("Current Directory :",pwd)