0% found this document useful (0 votes)
2 views

02.File Handling

Chapter 3 covers file handling in Python, explaining the concepts of files, streams, and the difference between text and binary files. It details how to open, close, and perform basic operations on files, including reading, writing, and appending data, as well as deleting files. The chapter also introduces file modes, functions for reading and writing data, and attributes related to file I/O.

Uploaded by

technokkbusiness
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

02.File Handling

Chapter 3 covers file handling in Python, explaining the concepts of files, streams, and the difference between text and binary files. It details how to open, close, and perform basic operations on files, including reading, writing, and appending data, as well as deleting files. The chapter also introduces file modes, functions for reading and writing data, and attributes related to file I/O.

Uploaded by

technokkbusiness
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

CHAPTER-3

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.

3.2 Data Files:


Data files can be stored in two ways:
1. Text Files: Text files are structured as a sequence of lines, where each line includes a
sequence of characters.
2. Binary Files : A binary file is any type of file that is not a text file.

S.
Text Files Binary Files
No.

Stores information in the same format


1. Stores information in ASCII characters. which the information is held in
memory.

Each line of text is terminated with a


2. special character known as EOL (End of No delimiters are used for a line.
Line)

Some internal translations take place


3. when this EOL character is read or No translation occurs in binary files.
written.

Binary files are faster and easier for a


4. Slower than binary files. program to read and write the text
files.

3.3 Opening and closing a file:


3.3.1 Opening a file:
To work with a file, first of all you have to open the file. To open a file in
python, we use open( ) function.
https://pythonschoolkvs.wordpress.com/ Page 13
The open( ) function takes two parameters; filename, and mode. open( ) function returns a file
object.
Syntax:
file_objectname= open(filename, mode)

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.

3.3.2 Closing a file:


After performing the operations, the file has to be closed. For this, a close( ) function is used to
close a file.
Syntax:
file-objectname.close( )

3.4 File Modes:

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.

‘w+’ ‘wb+’ Read and Write-File is created if does not exist.

‘a+’ ‘ab+’ Read and write-Append new data

‘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)

3.5 WORKING WITH TEXT FILES:

3.5.1 Basic operations with files:


a. Read the data from a file
b. Write the data to a file
c. Append the data to a file
d. Delete a file

a. Read the data from a file:


There are 3 types of functions to read data from a file.
 read( ) : reads n bytes. if no n is specified, reads the entire file.
 readline( ) : Reads a line. if n is specified, reads n bytes.
 readlines( ): Reads all lines and returns a list.

Steps to read data from a file:


 Create and Open a file using open( ) function
 use the read( ), readline( ) or readlines( ) function
 print/access the data
 Close the file. Create and Open a file

Read or Write data

Print/Access data

Close the file

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

Example-1: Program using read( ) function:

fin=open("D:\\python programs\\Book.txt",'r') fin=open("D:\\python programs\\Book.txt",'r')


str=fin.read( ) str=fin.read(10)
print(str) print(str)
fin.close( ) fin.close( )

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.

Example-2: using readline( ) function:


fin=open("D:\\python programs\\Book.txt",'r')
str=fin.readline( )
print(str)
fin.close( )
OUTPUT:
Python is interactive language. It is case sensitive language.

Example-3: using readlines( ) function:


fin=open("D:\\python programs\\Book.txt",'r')
str=fin.readlines( )
print(str)
fin.close( )
OUTPUT:
['Python is interactive language. It is case sensitive language.\n', 'It makes the difference
between uppercase and lowercase letters.\n', '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( )

Program-b: Count the number of words in a file.


fin=open("Book.txt",'r')
str=fin.read( )
L=str.split( )
count_words=0
for i in L:
count_words=count_words+1
print(count_words)
fin.close( )

Program-c: Count number of lines in a text file.


fin=open("Book.txt",'r')
str=fin.readlines()
count_line=0
for i in str:
count_line=count_line+1
print(count_line)
fin.close( )

Program-d: Count number of vowels in a text file.


fin=open("D:\\python programs\\Book.txt",'r')
str=fin.read( )
https://pythonschoolkvs.wordpress.com/ Page 17
count=0
for i in str:
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
count=count+1
print(count)
fin.close( )

Program-e : Count the number of ‘is’ word in a text file.

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

b. Write data to a file:


There are 2 types of functions to write the data to a file.

 write( ):Write the data to a file. Syntax:

write(string) (for text files)

write(byte_string) (for binary files)

 writelines( ): Write all strings in a list L as lines to file.

To write the data to an existing file, you have to use the following mode:

"w" - Write - will overwrite any existing content

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

c. Append the data to a file:


This operation is used to add the data in the end of the file. It doesn’t overwrite the existing
data in a file. To write the data in the end of the file, you have to use the following mode:

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")

Check if File exist:


To avoid getting an error, you might want to check if the file exists before you try to delete it:
Example
Check if file exists, then delete it:

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")

3.6 WORKING WITH BINARY FILES:


Binary files store data in the binary format (0’s and 1’s) which is understandable by the
machine. So when we open the binary file in our machine, it decodes the data and displays in a
human-readable format.

(a) Write data to a Binary File:


Example:
fout=open("story.dat","wb") # open file in write and binary mode
Norml_str= "Once upon a time"
encoded_str= Norml_str.encode ("ASCII") # encoding normal text
fout.write(encoded_str) # Write data in file
fout.close( )

Output:

(b) Read the data from Binary File:


Example:
fin=open("story.dat","rb") # open file in read and binary mode
str1= fin.read() # read the data from file
decoded_str=str1.decode("ASCII") # decode the binary data
print(decoded_str)
fin.close( )

https://pythonschoolkvs.wordpress.com/ Page 21
Output:
Once upon a time

3.7 tell( ) and seek( ) methods:


 tell( ): It returns the current position of cursor in file.
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
print(fout.tell( ))
fout.close( )

Output:
14

 seek(offset) : Change the cursor position by bytes as specified by the offset.

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

You might also like