02.File Handling
02.File Handling
FILE HANDLING
3.1 INTRODUCTION:
File:- A file is a collection of related data stored in a particular area on the disk.
Stream: - It refers to a sequence of bytes.
File handling is an important part of any web application.
S.
Text Files Binary Files
No.
Example:
To open a file for reading it is enough to specify the name of the file:
f = open("book.txt")
The code above is the same as:
f = open("book.txt", "rt")
Where "r" for read mode, and "t" for text are the default values, you do not need to specify
them.
Text Binary
file File Description
mode Mode
‘r’ ‘rb’ Read - Default value. Opens a file for reading, error if the file does not
exist.
‘w’ ‘wb’ Write - Opens a file for writing, creates the file if it does not exist
‘a’ ‘ab’ Append - Opens a file for appending, creates the file if it does not exist
‘r+’ ‘rb+’ Read and Write-File must exist, otherwise error is raised.
‘x’ ‘xb’ Create - Creates the specified file, returns an error if the file exists
https://pythonschoolkvs.wordpress.com/ Page 14
In addition you can specify if the file should be handled as binary or text mode
“t” – Text-Default value. Text mode
“b” – Binary- Binary Mode (e.g. images)
Print/Access data
https://pythonschoolkvs.wordpress.com/ Page 15
Let a text file “Book.txt” has the following text:
“Python is interactive language. It is case sensitive language.
It makes the difference between uppercase and lowercase letters.
It is official language of google.”
OUTPUT: OUTPUT:
Python is interactive language. It is case sensitive Python is
language.
It makes the difference between uppercase and
lowercase letters.
It is official language of google.
https://pythonschoolkvs.wordpress.com/ Page 16
Some important programs related to read data from text files:
Program-a: Count the number of characters from a file. (Don’t count white spaces)
fin=open("Book.txt",'r')
str=fin.read( )
L=str.split( )
count_char=0
for i in L:
count_char=count_char+len(i)
print(count_char)
fin.close( )
fin=open("D:\\python programs\\Book.txt",'r')
str=fin.read( )
L=str.split( )
count=0
for i in L:
if i=='is':
count=count+1
print(count)
fin.close( )
To write the data to an existing file, you have to use the following mode:
https://pythonschoolkvs.wordpress.com/ Page 18
Example: Open the file "Book.txt" and append content to the file:
fout= open("Book.txt", "a")
fout.write("Welcome to the world of programmers")
Example: Open the file "Book.txt" and overwrite the content:
fout = open("Book.txt", "w")
fout.write("It is creative and innovative")
Program: Write a program to take the details of book from the user and write the record
in text file.
fout=open("D:\\python programs\\Book.txt",'w')
n=int(input("How many records you want to write in a file ? :"))
for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )
OUTPUT:
How many records you want to write in a file ? :3
Enter details of record : 1
Enter the title of book : java
Enter price of the book: 250
Enter details of record : 2
Enter the title of book : c++
Enter price of the book: 300
Enter details of record : 3
Enter the title of book : python
Enter price of the book: 450
https://pythonschoolkvs.wordpress.com/ Page 19
"a" - Append - will append to the end of the file.
Program: Write a program to take the details of book from the user and write the record
in the end of the text file.
fout=open("D:\\python programs\\Book.txt",'a')
n=int(input("How many records you want to write in a file ? :"))
for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )
OUTPUT:
How many records you want to write in a file ? :2
Enter details of record : 1
Enter the title of book : DBMS
Enter price of the book: 350
Enter details of record : 2
Enter the title of book : Computer
Networking
Enter price of the book: 360
d. Delete a file: To delete a file, you have to import the os module, and use remove( )
function.
import os
os.remove("Book.txt")
https://pythonschoolkvs.wordpress.com/ Page 20
import os
if os.path.exists("Book.txt"):
os.remove("Book.txt")
else:
print("The file does not exist")
Output:
https://pythonschoolkvs.wordpress.com/ Page 21
Output:
Once upon a time
Output:
14
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
fout.seek(5)
print(fout.tell( ))
fout.close( )
Output:
5
3.8 File I/O Attributes
Attribute Description
name Returns the name of the file (Including path)
mode Returns mode of the file. (r or w etc.)
encoding Returns the encoding format of the file
closed Returns True if the file closed else returns False
https://pythonschoolkvs.wordpress.com/ Page 22
Example:
f = open("D:\\story.txt", "r")
print("Name of the File: ", f.name)
print("File-Mode : ", f.mode)
print("File encoding format : ", f.encoding)
print("Is File closed? ", f.closed)
f.close()
print("Is File closed? ", f.closed)
OUTPUT:
Name of the File: D:\story.txt
File-Mode : r
File encoding format : cp1252
Is File closed? False
Is File closed? True
https://pythonschoolkvs.wordpress.com/ Page 23