Python FILE HANDLING
Python FILE HANDLING
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 thenSVIMin \nitin “\n” will become
Ritesh Kushwah (Asst. Professor),
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”)
Mode
Mod
e
‘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 Read and File must exists otherwise error
‘rb+’ write is raised Both reading and
writing can take place
Ritesh Kushwah (Asst. Professor), SVIM
w+ ‘w+b’ or Write and File is created if not exists, if
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()
SAMPLE
FILE
Questions
…
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 theSyntax
Name file handle to Description
write
write() Filehandle.write(str1) Writes string str1 to file
desired content. referenced by filehandle
Writelines() Filehandle.writelines(L) Writes all string in List L as
lines to file referenced by
Ritesh Kushwah (Asst. Professor), SVIM
filehandle.
for more updates visit:
www.python4csip.com
Lets run
the same
program
again
Ritesh Kushwah (Asst. Professor), SVIM
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.
New content is
added after
previous
content
Ritesh Kushwah (Asst. Professor), SVIM
for more updates visit:
www.python4csip.com
Example- using
3: writelines()
record to file
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
Ritesh Kushwah (Asst. Professor), SVIM
Now content is
stored, because of
Ritesh Kushwah (Asst. Professor), SVIM close() function
pushed in
file are flushed
contents
for more updates visit:
www.python4csip.com
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.
Ritesh Kushwah (Asst. Professor), SVIM
for more updates visit:
www.python4csip.com
Exampl
e
myfile =
open(“ipl.txt”,”r”)
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.
Ritesh Kushwah (Asst. Professor), SVIM
for more updates visit:
www.python4csip.com
“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_statemen
t
The advantage of “with” is it will
automatically close the file after
Ritesh Kushwah (Asst. Professor), SVIM
nested block of code. It guarantees
for more updates visit:
www.python4csip.com
Exampl
e
Binary file
operations
If we want to write a structure such
as list or dictionary to a file and read
it subsequently we need to use the
Python module pickle. Pickling is
the process of converting structure
to a byte stream before writing to a
file and while reading the content of
file a reverse process called
Unpickling is used to convert the
byte stream back to the original
format.
Ritesh Kushwah (Asst. Professor), SVIM
for more updates visit:
www.python4csip.com
Example:
dump()
Example:
load()
Absolute Vs Relative
To understand PATH we must be
PATH
familiar with the terms: DRIVE,
FOLDER/DIRECTORY, FILES.
Our hard disk is logically divided
into many parts called DRIVES like
C DRIVE, D DRIVE etc.
Absolute Vs Relative
The drive is the main container in
PATH
which we put everything to store.
The naming format is :
DRIVE_LETTER:
For e.g. C: , D:
Drive is also known as ROOT
DIRECTORY.
Drive contains Folder and Files.
Folder contains sub-folders or files
Files are the actual data container.
Ritesh Kushwah (Asst. Professor), SVIM
for more updates visit:
www.python4csip.com
Absolute Vs Relative
PATH DRIV
E FOLDE
R
DRIVE/FOLDER/FILE
HIERARCHY
C:\
DRI E
V
SALES IT HR PROD
FOLD R FOLD R FOLD R FOLD R
E E E E
Absolute
Path
Absolute path is the full address of
any file or folder from the Drive i.e.
from ROOT FOLDER. It is like:
Drive_Name:\Folder\Folder…\
Forfilename
e.g. the Absolute of
path REVENUE.TXT will be file
C:\SALES\2018\
REVENUE.TXT
Absolute path of
SEC_12.PPT is
Ritesh Kushwah (Asst. Professor), SVIM
C:\PROD\NOIDA\
for more updates visit:
www.python4csip.com
Relative
Path
Relative Path is the location of
file/folder from the current folder.
To use Relative path special
symbols are:
Single Dot ( . ) : single dot ( . )
refers to current folder.
Double Dot ( .. ) : double dot ( .. )
refers to parent folder
Backslash ( \ ) : first backslash
before (.) and double
dot(
Ritesh .. (Asst.
Kushwah ) Professor), SVIM refers to ROOT
for more updates visit:
www.python4csip.com
Relative
addressing
Current working
directory C:\
DRIV
E
SALE IT H PRO
S R D
FOLDE FOLDE FOLDE FOLDE
R R R R
.\2019\SHEET.XLS
Ritesh Kushwah (Asst. Professor), SVIM
for more updates visit:
www.python4csip.com
Relative
addressing Current
working
C:\ directory
DRIV
E
SALE IT H PRO
S R D
FOLDE FOLDE FOLDE FOLDE
R R R R