Chapter 14 Python
Chapter 14 Python
******************Chapter-14***********************
**************************************************
***************14.File Handling ********************:-
………………………………………………………………………………………………
As the part of programming requirement, we have to store
our data permanently for future purpose. For this
requirement we should go for files.
………………………………………………………………………………………………
***********Opening a File:***********
………………………………………………………………………………………..
Before performing any operation (like read or write) on the
file,first we have to open that file.For this we should use
Python's inbuilt function open()
f = open(filename, mode)
4. r+ -> To read and write data into the file. The previous data
in the file will not be deleted.The file pointer is placed at the
beginning of the file.
f = open("abc.txt","w")
f.close()
……………………………………………………………………………………
***********Various properties of File Object:********
……………………………………………………………………………………..
Once we opend a file and we got file object,we can get
various details related to that file by using its properties.
write(str)
writelines(list of lines)
………………………………………………………………….
Eg:
1) f=open("abcd.txt",'w')
2) f.write("prasanna\n")
3) f.write("Software\n")
4) f.write("Solutions\n")
5) print("Data written to the file successfully")
6) f.close()
…………………………………………………………………
abcd.txt:
prasanna
Software
Solutions
…………………………………………………………………………….
Note: In the above program, data present in the file will be
overridden everytime if we run the program. Instead of
overriding if we want append operation then we should open
the file as follows.
f = open("abcd.txt","a")
……………………………………………………………….
Eg 2:
1) f=open("abcd.txt",'w')
2) list=["sunny\n","bunny\n","vinny\n","chinny"]
3) f.writelines(list)
4) print("List of lines written to the file successfully")
5) f.close()
………………………………………………………………
abcd.txt:
sunny
bunny
vinny
chinny
………………………………………………………………………………
Note: while writing data by using write() methods,
compulsory we have to provide line seperator(\n),otherwise
total data should be written to a single line.
…………………………………………………………………………………
********Reading Character Data from text files:******:-
………………………………………………………………………………………..
We can read character data from text file by using the
following read methods.
Output: 0 su 2 nny 5
…………………………………………………………………………………….
seek():
……………………
We can use seek() method to move cursor(file pointer) to
specified location.
[Can you please seek the cursor to a particular location]
f.seek(offset, fromwhere)
with open("emp.csv","w",newline='') as f:
with open("emp.csv","w") as f:
……………………………………………………………………………………..
Note: If we are not using newline attribute then in the csv file
blank lines will be included between data. To prevent these
blank lines, newline attribute is required in Python-3,but in
Python-2 just we can specify mode as 'wb' and we are not
required to use newline attribute.
………………………………………………………………………………………
**************Reading Data from csv file:*********
……………………………………………………………………………………….
1) import csv
2) f=open("emp.csv",'r')
3) r=csv.reader(f) #returns csv reader object
4) data=list(r)
5) #print(data)
6) for line in data:
7) for word in line:
8) print(word,"\t",end='')
9) print()
10)
11) Output
12) D:\Python_classes>py test.py
13) ENO ENAME ESAL EADDR
14) 100 prasanna 1000 Hyd
15) 200 Sachin 2000 Mumbai
16) 300 Dhoni 3000 Ranchi
………………………………………………………………………………………
********Zipping and Unzipping Files: ********
……………………………………………………………………………………….
It is very common requirement to zip and unzip files. The
main advantages are:
f = ZipFile("files.zip","w","ZIP_DEFLATED")
f.write(filename)
………………………………………………………………………………………….
Eg:
1) from zipfile import *
2) f=ZipFile("files.zip",'w',ZIP_DEFLATED)
3) f.write("file1.txt")
4) f.write("file2.txt")
5) f.write("file3.txt")
6) f.close()
7) print("files.zip file created successfully")
/…………………………………………………………………………………
***********To perform unzip operation:***********
…………………………………………………………………………………….
names = f.namelist()
………………………………………………………………………………….
Eg:
1) from zipfile import *
2) f=ZipFile("files.zip",'r',ZIP_STORED)
3) names=f.namelist()
4) for name in names:
5) print( "File Name: ",name)
6) print("The Content of this file is:")
7) f1=open(name,'r')
8) print(f1.read())
9) print()
………………………………………………………………………………………………
*********Working with Directories:********************
…………………………………………………………………………………………..
It is very common requirement to perform operations for
directories like
cwd
|-mysub
|-mysub2
import os
os.mkdir("mysub/mysub2")
print("mysub2 created inside mysub")
……………………………………………………………………….
Note: Assume mysub already present in cwd.
……………………………………………………………………..
Q4. To create multiple directories like sub1 in that sub2 in
that sub3:
import os
os.makedirs("sub1/sub2/sub3")
print("sub1 and in that sub2 and in that sub3 directories
created")
………………………………………………………………………
Q5. To remove a directory:
import os
os.rmdir("mysub/mysub2")
print("mysub2 directory deleted")
………………………………………………………………………….
Q6. To remove multiple directories in the path:
…………………………..
import os
os.removedirs("sub1/sub2/sub3")
print("All 3 directories sub1,sub2 and sub3 removed")
……………………………………………………………………………..
Q7. To rename a directory:
import os
os.rename("mysub","newdir")
print("mysub directory renamed to newdir")
…………………………………………………………………………….
Q8. To know contents of directory:
…………………………………………………………
os module provides listdir() to list out the contents of the
specified directory. It won't display the contents of sub
directory.
Eg:
1) import os
2) print(os.listdir("."))
3)
4) Output
5) D:\Python_classes>py test.py
6) ['abc.py', 'abc.txt', 'abcd.txt', 'com', 'demo.py', ' prasanna
math.py', 'emp.csv', '
7) file1.txt', 'file2.txt', 'file3.txt', 'files.zip', 'log.txt',
'module1.py', 'myl
8) og.txt', 'newdir', 'newpic.jpg', 'pack1', 'rossum.jpg',
'test.py', '__pycache__'
9) ]
os.walk(path,topdown=True,onerror=None,followlinks=False)
Eg:
import os
os.system("dir *.py")
os.system("py abc.py")
………………………………………………………………………………………….
*********How to get information about a File:*******
…………………………………………………………………………………………
We can get statistics of a file like size, last accessed time,last
modified time etc by using stat() function of os module.
stats = os.stat("abc.txt")
st_mode==>Protection Bits
st_ino==>Inode number
st_dev===>device
st_nlink===>no of hard links
st_uid===>userid of owner
st_gid==>group id of owner
st_size===>size of file in bytes
st_atime==>Time of most recent access
st_mtime==>Time of Most recent modification
st_ctime==> Time of Most recent meta data change
………………………………………………………………………….
Note:
st_atime, st_mtime and st_ctime returns the time as number
of milli seconds since Jan 1st 1970 ,12:00AM. By using
datetime module fromtimestamp() function,we can get exact
date and time.
………………………………………………………………………………………
Q. To print all statistics of file abc.txt:
1) import os
2) stats=os.stat("abc.txt")
3) print(stats)
4)
5) Output
6) os.stat_result(st_mode=33206, st_ino=844424930132788,
st_dev=2657980798, st_nlin
7) k=1, st_uid=0, st_gid=0, st_size=22410,
st_atime=1505451446, st_mtime=1505538999
8) , st_ctime=1505451446)
………………………………………………………………………………
Q. To print specified properties:
1) import os
2) from datetime import *
3) stats=os.stat("abc.txt")
4) print("File Size in Bytes:",stats.st_size)
5) print("File Last Accessed
Time:",datetime.fromtimestamp(stats.st_atime))
6) print("File Last Modified
Time:",datetime.fromtimestamp(stats.st_mtime))
7)
8) Output
9) File Size in Bytes: 22410
10) File Last Accessed Time: 2017-09-15 10:27:26.599490
11) File Last Modified Time: 2017-09-16 10:46:39.245394
….……………………………………………………………………………………….…
*******************END***************************
……………………………………………………………………………………………..