File Handling_Theory
File Handling_Theory
CHAPTER-4 : FILE HANDLING
Introduction :
File : A file is a collection of related data stored in computer storage for future data retrieval.
Stream : It refers to a sequence of bytes.
File handling refers to reading and writing contents from a file.
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.
1. Stores information in ASCII characters. Stores information in the same format which
the information is held in memory.
2. Each line of text is terminated with a special No delimiters are used for a line.
character known as EOL (End of Line)
3. Some internal translations take place when No translation occurs in binary files.
this EOL character is read or written.
4. Slower than binary files. Binary files are faster and easier for a
program to read and write the text files.
Opening and closing a file :
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. 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.
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( )
E 53
Computer Science/Python
FILE MODES
Text file Binary 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
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)
WORKING WITH TEXT FILES
Basic operations with files:
(a) Read the data from a file Create and Open a file
(b) Write the data to a file
(c) Append the data to a file
(d) Delete a file Read or Write data
54 E
CBSE
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 Python is
sensitive 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.']
□ 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( )
E 55
Computer Science/Python
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()
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( )
(a) 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
56 E
CBSE
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")
fout.close()
Example: Open the file "Book.txt" and overwrite the content:
fout = open("Book.txt", "w")
fout.write("It is creative and innovative")
fout.close()
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:
E 57
Computer Science/Python
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
WORKING WITH BINARY FILES
Binary files are used to store binary data such as images, video files, audio files etc. They store
data in the binary format (0‟s and 1‟s) .In Binary files there is no delimiter for a line. To open
files in binary mode, when specifying a mode, add 'b' to it. Pickle module can be imported to
write or read data in a binary file.
(a) Write data to a Binary File:
Example:
import pickle
e={'Namita':25000,'Manya': 30000,'Tanu': 20000}
f1=open('emp.dat','wb')
pickle.dump(e,f1)
f1.close()
OUTPUT:
A file named emp.dat will be created in current working directory.
58 E
CBSE
(b) Read the data from Binary File:
Example :
import pickle
f1=open('emp.dat','rb')
e=pickle.load(f1)
for x in e:
print(x)
f1.close()
OUTPUT :
Namita
Manya
Tanu
Example :
import pickle
®
f1=open('emp.dat','rb')
e=pickle.load(f1)
for x in e:
if(e[x]>=25000 and e[x]<=30000):
print(x)
f1.close()
OUTPUT :
Employee having salary between 2500 to 30000
Namita
Manya
E 59
Computer Science/Python
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
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
Relative and Absolute Paths:
• We all know that the files are kept in directory which are also known as folders.
• Every running program has a current directory. Which is generally a default directory and
python always see the default directory first.
• The absolute paths are from the topmost level of the directory structure. The relative paths are
relative to the current working directory denoted as a dot(.) while its parent directory is denoted
with two dots(..).
• OS module provides many such functions which can be used to work with files and directories.
OS means Operating System.
• getcwd( ) is a very function which can be used to identify the current working directory
>>> import os
>>> cwd=os.getcwd()
>>> print(cwd)
C:\Users\kv2kkdSrSec\AppData\Local\Programs\Python\Python36-32
60 E
CBSE
STANDARD FILE STREAMS
• We use standard I/O Streams to get better performance from different I/O devices.
• Some Standard Streams in python are as follows –
– Standard input Stream sys.stdin
– Standard output Stream sys.stdout
– Standard error Stream sys.stderr
import sys
f=open(r"hello.txt")
line1=f.readline()
line2=f.readline()
line3=f.readline()
sys.stdout.write(line1)
sys.stdout.write(line2)
®
sys.stdout.write(line3)
sys.stderr.write("\nNo errors occured\n")
f.close()
PYTHON CSV
We will learn how to read and write into CSV files in Python with the help of examples.
A CSV (Comma Separated Values) format is one of the most simple and common ways to store
tabular data. To represent a CSV file, it must be saved with the .csv file extension.
Let's take an example :
If you open the above CSV file using a text editor such as sublime text, you will see :
SN, Name, City
1. Michael, New Jersey
2. Jack, California
As you can see, the elements of a CSV file are separated by commas. Here, is a delimiter.
You can have any single character as your delimiter as per your needs.
Note : The csv module can also be used for other file extensions (like: .txt) as long as their
contents are in proper structure.
Working with CSV files in Python
While we could use the built-in open() function to work with CSV files in Python, there is a
dedicated csv module that makes working with CSV files much easier.
Before we can use the methods to the csv module, we need to import the module first using:
import csv
________________________________________
Reading CSV files Using csv.reader()
To read a CSV file in Python, we can use the csv.reader() function. Suppose we have a csv file
named people.csv in the current directory with the following entries.
Name Age Profession
Jack 23 Doctor
Miller 22 Engineer
Let's read this file using csv.reader():
E 61
Computer Science/Python
Example 1 : Read CSV Having Comma Delimiter
import csv
with open('people.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
Output
['Name', 'Age', 'Profession']
['Jack', '23', 'Doctor']
['Miller', '22', 'Engineer']
Here, we have opened the people.csv file in reading mode using:
with open('people.csv', 'r') as file: .......
®
To learn more about opening files in Python, visit: Python File Input/Output Then, the
csv.reader() is used to read the file, which returns an iterable reader object.
The reader object is then iterated using a for loop to print the contents of each row.
________________________________________
In the above example, we are using the csv.reader() function in default mode for CSV files
having comma delimiter.
However, the function is much more customizable.
Suppose our CSV file was using tab as a delimiter. To read such files, we can pass optional
parameters to the csv.reader() function. Let's take an example.
Example 2 : Read CSV file Having Tab Delimiter
import csv
with open('people.csv', 'r',) as file:
reader = csv.reader(file, delimiter = '\t')
for row in reader:
print(row)
Notice the optional parameter delimiter = '\t' in the above example.
________________________________________
The complete syntax of the csv.reader() function is :
csv.reader(csvfile, dialect='excel', **optional_parameters)
As you can see from the syntax, we can also pass the dialect parameter to the csv.reader()
function. The dialect parameter allows us to make the function more flexible. To learn more,
visit: Reading CSV files in Python.
________________________________________
Writing CSV files Using csv.writer()
To write to a CSV file in Python, we can use the csv.writer() function.
The csv.writer() function returns a writer object that converts the user's data into a delimited
string. This string can later be used to write into CSV files using the writerow() function. Let's
take an example.
62 E
CBSE
Example 3 : Write to a CSV file
import csv
with open('protagonist.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["SN", "Movie", "Protagonist"])
writer.writerow([1, "Lord of the Rings", "Frodo Baggins"])
writer.writerow([2, "Harry Potter", "Harry Potter"])
When we run the above program, a protagonist.csv file is created with the following content:
SN,Movie,Protagonist
1. Lord of the Rings, Frodo Baggins
2. Harry Potter, Harry Potter
In the above program, we have opened the file in writing mode.
®
Then, we have passed each row as a list. These lists are converted to a delimited string and written
into the CSV file.
________________________________________
Example 4 : Writing multiple rows with writerows()
If we need to write the contents of the 2-dimensional list to a CSV file, here's how we can do it.
import csv
csv_rowlist = [["SN", "Movie", "Protagonist"], [1, "Lord of the Rings", "Frodo Baggins"],
[2, "Harry Potter", "Harry Potter"]]
with open('protagonist.csv', 'w') as file:
writer = csv.writer(file)
writer.writerows(csv_rowlist)
The output of the program is the same as in Example 3.
Here, our 2-dimensional list is passed to the writer.writerows() method to write the content of the
list to the CSV file.
E 63