Sunteți pe pagina 1din 31

Python Programming

FILE
HANDLING

11/2/2019 Dr. D.P.Sharma 2


Introduction and Types of Files
§ As the part of programming requirement, we have to store our data permanently for
future purpose. For this requirement we should go for files.
§ Files are very common permanent storage areas to store our data.

Types of Files:

1) Text Files:
Usually we can use text files to store character data. Eg: abc.txt

2) Binary Files:
Usually we can use binary files to store binary data like images, video
files, audio files etc..

11/2/2019 Dr. D.P.Sharma 3


Opening a File and various File modes:

§ 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().

§ But at the time of open, we have to specify mode, which represents the purpose of
opening file.
f = open(filename, mode)

§ The allowed modes in Python are:

11/2/2019 Dr. D.P.Sharma 4


Opening a File and various File modes:

§ r = open an existing file for read operation. The file pointer is positioned at the
beginning of the file. If the specified file does not exist then we will get
FileNotFoundError. This is default mode.

§ W = open an existing file for write operation. If the file already contains some data
then it will be overridden. If the specified file is not already available then this mode
will create that file.

§ a = open an existing file for append operation. It won't override existing data. If the
specified file is not already available then this mode will create a new file.

§ 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.

11/2/2019 Dr. D.P.Sharma 5


Opening a File and various File modes:

§ w+ = To write and read data. It will override existing data.

§ a+ = To append and read data from the file. It wont override existing data.

§ x = To open a file in exclusive creation mode for write operation. If the file already
exists then we will get FileExistsError.

11/2/2019 Dr. D.P.Sharma 6


Closing a File

§ After completing our operations on the file, it is highly recommended to close the file.

§ For this we have to use close() function.

f.close()

11/2/2019 Dr. D.P.Sharma 7


Various Properties of File Object:
Once we opened a file and we got file object, we can get various details related
to that file by using its properties.

§ name = Name of opened file.

§ mode = Mode in which the file is opened.

§ closed = Returns boolean value indicates that file is closed or not.

§ readable() = Returns boolean value indicates that whether file is readable or not.

§ writable() = Returns boolean value indicates that whether file is writable or not.

11/2/2019 Dr. D.P.Sharma 8


Various Properties of File Object:

1) f=open("abc.txt",'w')
2) print("File Name: ",f.name) Output
3) print("File Mode: ",f.mode)
4) print("Is File Readable: ",f.readable()) File Name: abc.txt
5) print("Is File Writable: ",f.writable()) File Mode: w
6) print("Is File Closed : ",f.closed) Is File Readable: False
Is File Writable: True
7) f.close() Is File Closed: False
8) print("Is File Closed : ",f.closed) Is File Closed: True

11/2/2019 Dr. D.P.Sharma 9


Writing Character Data to Text Files:
We can write character data to the text files by using the following two methods.

1) write(str)
2) writelines(list of lines) O/P:

1) f=open("abcd.txt",'w') Data written to the file successfully


2) f.write("DP\n")
3) f.write("Sharma\n")
4) f.write(“Manipal\n") Note: In the above program, data present in the file
5) f.close() will be overridden every time if we run the program.
6) print("Data written to the file successfully") Instead of overriding if we want append operation
then we should open the file as follows.
DP
Sharma f = open("abcd.txt","a")
Manipal

11/2/2019 Dr. D.P.Sharma 10


Writing Character Data to Text Files:
We can write character data to the text files by using the following two methods.

1) write(str)
2) writelines(list of lines) Sunny
Bunny
Vinny
chinny
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()

Note: While writing data by using write()/writelines() methods, compulsory we have to provide line separator(\n),
otherwise, total data should be written to a single line.

11/2/2019 Dr. D.P.Sharma 11


Writing Character Data to Text Files:
In case of dict, only keys will be added. Instead of keys , if we want to add values, then
we have to write the code explicitly.

D={100:”DPSharma”,200::”Rahul”}
f.writelines([D[100],D[200])

OR

D={100:”DPSharma”,200::”Rahul”}
f.writelines(D.values())

11/2/2019 Dr. D.P.Sharma 12


File Handling:

11/2/2019 Dr. D.P.Sharma 13


Reading Character Data from Text Files:

We can read character data from text file by using the following read methods.

§ read() = To read total data from the file.

§ read(n) = To read 'n' characters from the file.

§ readline() = To read only one line.

§ readlines() = To read all lines into a list

11/2/2019 Dr. D.P.Sharma 14


Reading Character Data from Text Files:
To read total data from the file
by using read() method.

1) f=open("abc.txt",'r')
2) data=f.read()
3) print(data)
4) f.close()

Output
sunny
bunny
chinny
vinny

11/2/2019 Dr. D.P.Sharma 15


Reading Character Data from Text Files:
To read 'n' characters from the file
by using read(n) method.
§ While reading the data , newline character for each line will be
1) f=open("abc.txt",'r') added.
2) data=f.read(10) § If the specified number of characters are not available in the
3) print(data) file then only available characters we will get.
4) f.close()
data=f.read(10000)

Output § If we are passing –ve value as an argument, then we will get


sunny total file.

bunn data=f.read(-1)

§ For any –ve value , result is always same.

11/2/2019 Dr. D.P.Sharma 16


Reading Character Data from Text Files:
To read data line by line
by using readline() method.
§ If control reaches end of file (i.e. if there is no next line in
the file), then readline () method returns empty string.
1) f=open("abc.txt",'r')
F=fopen(“abc.txt”,”r”)
2) line1=f.readline() Line=F.readline()
3) print(line1,end='') while Line!=“”:
4) line2=f.readline() print(Line,end=“”)
5) print(line2,end='') Line=F.readline()
F.close()
6) line3=f.readline()
7) print(line3,end='')
8) f.close()

11/2/2019 Dr. D.P.Sharma 17


Reading Character Data from Text Files:
To read all lines into list:
by using readlines() method.

§ Here each read line will be the one separate element of


1) f=open("abc.txt",'r') the list (including newline character).
2) lines=f.readlines()
3) for line in lines:
4) print(line,end='')
5) f.close()

11/2/2019 Dr. D.P.Sharma 18


Reading Character Data from Text Files:
To use all the read methods in one programme:
Yes , we can use all the methods in one programme but not recommended .

1) f=open("abc.txt","r")
2) print(f.read(3))
3) print(f.readline())
4) print(f.read(4))
5) print("Remaining data")
6) print(f.read())

11/2/2019 Dr. D.P.Sharma 19


The with Statement:
§ The with statement can be used
while opening a file. We can use 1) with open("abc.txt","w") as f:
this to group file operation 2) f.write("DP\n")
statements within a block. 3) f.write("Sharma\n")
4) f.write(“Python\n")
5) print("Is File Closed: ",f.closed)
§ The advantage of with statement 6) print("Is File Closed: ",f.closed)
is, it will take care closing of file
automatically once control reaches
end of the with block. Even in the Output:
case of exceptions also, file will be
closed automatically and we are Is File Closed: False
not required to close explicitly. Is File Closed: True

11/2/2019 Dr. D.P.Sharma 20


The with Statement:
§ Q1. What is the advantage of using with block while opening a file?.

§ Ans : After completing our operations on the file, the file will be closed automatically and we are not
required to close explicitly.

§ Q2. What is the difference between:


F=open(‘abc.txt’,’w’):
and
with open(‘abc.txt’,’w’) as F:

§ Ans : F=open(‘abc.txt’,’w’):
In this case , we have to close the file explicitly.

§ Ans : with open(‘abc.txt’,’w’) as F:


In this case, we are not require to close the file explicitly and it will be close automatically.

11/2/2019 Dr. D.P.Sharma 21


The seek() and tell() Methods:
tell():
§ tell() will return the current position of the cursor (file pointer), with reference to
beginning of the file.
[ can you plese telll current cursor position]

§ The position(index) of first character in files is zero just like string index.

1) f=open("abc.txt","r") Output: Assume the


2) print(f.tell()) 0 content of abc.txt:
3) print(f.read(2)) su sunny
4) print(f.tell())
2 bunny
5) print(f.read(3))
6) print(f.tell()) nny chinny
5 vinny

11/2/2019 Dr. D.P.Sharma 22


The seek() and tell() Methods:
seek()—Python(2.X):
§ We can use seek() method to move cursor (file pointer) to specified index location.
[Can you please seek the cursor to a particular location]

§ f.seek(offset, fromwhere) == offset represents the number of positions

§ The allowed Values for 2nd Attribute (from where) are

0 == From beginning of File (Default Value)


1 == From Current Position
2 == From end of the File

NOTE: All allowed 3 Values for 2nd Attribute is supported in PYTHON-2 not in PYTHON -3.

11/2/2019 Dr. D.P.Sharma 23


The seek() and tell() Methods:
seek()—Python(3.X):
NOTE: PYTHON -3 supports only zero, i.e. no need to pass second argument.

data="All Students are SMART"


f=open("abc.txt","w")
f.write(data) Output:
with open("abc.txt","r+") as f:
text=f.read() All Students are SMART
print(text) The Current Cursor Position: 22
print("The Current Cursor Position: ",f.tell()) The Current Cursor Position: 17
f.seek(17)
Data After Modification:
print("The Current Cursor Position: ",f.tell())
f.write("GEMS!!!")
All Students are GEMS!!!
f.seek(0)
text=f.read()
print("Data After Modification:")
print(text)

11/2/2019 Dr. D.P.Sharma 24


How to check a particular File exists OR not?
§ We can use os library to get information about files in our computer.
§ os module has path sub module, which contains isFile() function to check whether a
particular file exists or not?
os.path.isfile(fname)

1) import os,sys
2) fname=input("Enter File Name: ") Note:
3) if os.path.isfile(fname):
4) print("File exists:",fname)
§ sys.exit(0)== To exit system without
5) f=open(fname,"r")
6) else: executing rest of the program.
7) print("File does not exist:",fname)
8) sys.exit(0) § argument represents status code. 0 means
9) print("The content of file is:") normal termination and it is the default
10) data=f.read() value.
11) print(data)

11/2/2019 Dr. D.P.Sharma 25


Program to print the Number of Lines, Words and Characters present in the given File

1) import os,sys 10) for line in f:


2) fname=input("Enter File Name: ") 11) lcount=lcount+1
3) if os.path.isfile(fname): 12) ccount=ccount+len(line)
4) print("File exists:",fname) 13) words=line.split()
5) f=open(fname,"r") 14) wcount=wcount+len(words)
6) else: 15) print("The number of Lines:",lcount)
7) print("File does not exist:",fname) 16) print("The number of Words:",wcount)
8) sys.exit(0) 17) print("The number of Characters:",ccount)
9) lcount=wcount=ccount=0

11/2/2019 Dr. D.P.Sharma 26


Handling Binary Data:
§ It is very common requirement to read or write binary data like images, video files,
audio files etc.

Q) Program to read Image File and write to a New Image File?

1) f1=open("rossum.jpg","rb")
2) f2=open("newpic.jpg","wb")
3) bytes=f1.read()
4) f2.write(bytes)
5) print("New Image is available with the name: newpic.jpg")

11/2/2019 Dr. D.P.Sharma 27


Handling CSV Files

§ CSV=== Coma Separated Values.

§ As the part of programming , it is very common requirement to write and read data
to /from csv files.

§ Python provides csv module to handle csv files.

11/2/2019 Dr. D.P.Sharma 28


Handling CSV Files--Writing Data to CSV File
import csv
with open('emp.csv','w',newline='') as f:

w=csv.writer(f) #returns writer object to write data


#print(type(w)) #<class '_csv.writer'>
w.writerow(['ENO','ENAME','ESAL','EADDR'])
while True:
eno=int(input('Enter Employee Number:'))
ename=input('Enter Employee Name:')
esal=float(input('Enter Employee Salary:'))
eaddr=input('Enter Employee Address:')
w.writerow([eno,ename,esal,eaddr])
option=input('Do You want to insert one more record [Yes|No]:')
if option.lower()=='no':
break

print('Total Employees data written to csv file successfully')

11/2/2019 Dr. D.P.Sharma 29


Handling CSV Files--Writing Data to CSV File

Note:
Observe the difference with newline attribute and without newline attribute

with open("emp.csv","w",newline='') as f:
Vs
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 each record/row.

§ 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.

11/2/2019 Dr. D.P.Sharma 30


Handling CSV Files—Reading Data from CSV File

import csv
with open('emp.csv','r') as f:

r=csv.reader(f) #returns csv reader object


#print(type(r)) #<class '_csv.reader'>
data=list(r)
#print(data)
for row in data:
for column in row:
print(column,'\t',end='')
print()

11/2/2019 Dr. D.P.Sharma 31

S-ar putea să vă placă și