Professional Documents
Culture Documents
F 12 CH 04 TEXT FILE HANDLING 1
F 12 CH 04 TEXT FILE HANDLING 1
(a) Write a statement in Python to open a text file WRITEUP.TXT so that new
content can be written in it.
OR
(a)Write a statement in Python to open a text file README.TXT so that existing
content can be read from it.
OR
Write a statement in python to perform the following operations :
1] to open a text file “BOOK.txt” in read mode
2] to open a text file “BOOK.txt” in write mode
Or
(a) Differentiate between file modes r+ and w+ with respect to Python.
2- marks Question
Write a function in python to count the number of lines in a text file ‘STORY.TXT’ ,
which is starting with an alphabet ‘A’ .
OR
Write a method/function DISPLAYWORDS() in python to read lines from a text
file STORY.TXT, and display those words, which are less than 4 characters.
OR
Write a function count_me_my() in python to read the text file “Data.txt” and count the
number of times “me” and “My”.
OR
Write a method/function AEDISP() in python to read lines from a text file WRITER.TXT,
and display those lines, which are starting either with A or starting with E.
OR
Write a method/function ISTOUPCOUNT() in python to read contents from a text file
WRITER.TXT, to count and display the occurrence of the word ‘‘IS’’ or ‘‘TO’’ or ‘‘UP’’.
OR
Write method in Python to read lines from a text file DIARY.TXT, and display those lines,
which are starting with an alphabet ‘P’.
05- marks question
A binary file “Book.dat” has structure [BookNo, Book_Name,
Author, Price].
i. Write a user defined function CreateFile() to input data for a
record and add to Book.dat .
ii. Write a function CountRec(Author) in Python which accepts the
Author name as parameter and count and return number of books by
the given Author are stored in the binary file “Book.dat”
OR
A binary file “STUDENT.DAT” has structure (admission_number,
Name, Percentage).
Write a function countrec() in Python that would read contents of the
file “STUDENT.DAT” and display the details of those students
whose percentage is above 75. Also display number of students
scoring above 75%
CBSE QUESTION PATTERN OF FILE HANDLING
These data can be stored in a file. Whenever users need such data,
data can be presented by files.
When you develop a program in python, the final output of the
program is not available for future use. Data files serve this purpose.
Python allow us to read data from and save data to external text
files permanently on secondary storage media.
File:-
A file is a stream or sequence of characters/data occupying
named place on the disk where a sequence of related data
is stored.
Flow of Data
File I/O [input/ouput] means Transfer of data from
Secondary Memory to [Hard Disk] to Main Memory or
Vice versa .
Types of File in Python:
Before we discuss file operation we should be aware
of the file types. Python allows us to create and
manage three types of data files.
1- Text file
2- Binary file
3- CSV file
Data File Types
1] Text file
It is a file that stores information in ASCII characters. In text files, each line of text
is terminated with a special character known as EOL (End of Line) character or
delimiter character. When this EOL character is read or written, certain internal
translations take place.
2] Binary file
It is a file that contains information in the same format as it is held in memory. In
binary files, no delimiters are used for a line and no translations occur
here. Binary files are used to store binary data such as images, video files, audio
files, etc.
Binary files in Python
Most of the files that we see in our computer system are called binary files.
Example:
•Document files: .pdf, .doc, .xls etc.
•Image files: .png, .jpg, .gif, .bmp etc.
•Video files: .mp4, .3gp, .mkv, .avi etc.
•Audio files: .mp3, .wav, .mka, .aac etc.
•Database files: .mdb, .accde, .frm, .sqlite etc.
•Archive files: .zip, .rar, .iso, .7z etc.
•Executable files: .exe, .dll, .class etc.
For handling such binary files we need a specific type of software to open it.
For Example, You need Microsoft word software to open .doc binary files. Likewise,
you need a pdf reader software to open .pdf binary files and you need a photo
editor software to read the image files and so on.
Text files in Python
Text files don’t have any specific encoding and it can be opened in
normal text editor itself.
Example:
•Web standards: html, XML, CSS, JSON etc.
•Source code: c, app, js, py, java etc.
•Documents: txt, tex, RTF etc.
•Tabular data: csv, tsv etc.
•Configuration: ini, cfg, reg etc.
Data File Operations
The operations performed on a file is called the file
operation. Following is the list of operations can be applied
on a file in python.
Basic file operations :-
1] Opening a File
2] Performing Operations [read , write etc.]
3] Closing a file
Data File Operations
We can process file in several ways such as:
1] creating a file
2] Traversing a file to display contents
3] appending data in a file
4] inserting data in file
5] deleting data from a file
6] Creating a copy of a file
7] updating data in a file etc.
Modes of opening the file :-
Opening and Closing a Text File
Open a File:-
To open a file, you need to use the built-in open function. The open
function returns a file object that contains methods and attributes to
perform various operations on the file.
Syntax :
file_object = open("filename", "mode")
Here,
filename: gives name of the file that the file object has opened.
mode: attribute of a file object tells you which mode a file was
opened in.
Modes of opening the file :-
The access mode is the string which tells in what mode the file
should be opened for operations. There are three different access
modes are available in python.
rb - Opens a binary file for Reading in binary format. The file pointer
is placed at the beginning of the file.
r+ - Opens a text file for Reading and Writing. The file pointer is
placed at the beginning of the file.
rb+ - Opens a binary file for Reading and Writing in binary format.
The file pointer is placed at the beginning of the file.
Concept of File mode :
wb+ - Opens a binary file for Reading and Writing in binary format,
If file doesn’t exist ,creates a new file.
Concept of File mode :
Append Mode
a - Opens a text file for appending, the file pointer is at the end of the file ,if the
file is doesn’t exist ,it create new file.
ab - Opens a binary file for appending in binary format, the file pointer is at the
end of the file ,if the file is doesn’t exist ,it create new file.
a+ - Opens a text file for appending and reading. The file pointer is at the end of
the file. the file pointer is at the end of the file ,if the file is doesn’t exist ,it create
new file.
ab+ - Opens a binary file for appending and reading in binary format. The file
pointer is at the end of the file. the file pointer is at the end of the file ,if the file is
doesn’t exist ,it create new file.
Concept of File mode :
Opening and Closing a Text File
Concept of File mode :
1] write(string) :
write() method takes a string as an argument and writes
it to the text file. It returns the number of characters
being written on single execution of the write() method.
Example:
# Python code to create a file
file = open(‘c:\test.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
Writing to File
Example
f = open('myfile.txt', 'w')
lines = ['New line 1\n', 'New line 2\n', 'New line 3']
f.writelines(lines)
OUTPUT:
myfile.txt
New line 1
New line 2
New line 3
Reading From File :-
Python provides various methods for reading data from a
file . Lets see:
1] read() : to read the entire data from the file.
OUTPUT:
Enter the Name Ashok Kumar
Enter the Age55
Student In
[activity-3] Reading From File :- with readline() function
OUTPUT:
Enter the NameRajendra
Enter the Age88
1. Student Information
Rajendra
Reading From File :- with readlines() function ]\
OUTPUT:
Enter the Nameram kumar
Enter the Age55
1. Student Information
ram kumar
55
#program to count no. of lines from a text file.#
OUTPUT :
Total No. of Lines in File= 3
#program to input info. Of students and display it.
#python data file : with statement
the above with statement will automatically close the file after the nested
block of code.
1] if the file already exits , it will not be erased . If the file does
not exist , it will be created.
OUTPUT:
Name:-Amit Kumar
Address :- MG road Indore
Job Title : Testing Eng.
Company :-TCS
Job Description:- Testing the Code
Appending to File :-
To append data into a file we must open the file in ‘a+’ mode so that we will
have access to both the append as well as write modes.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“Strawberry”)
The above code appends the string ‘Strawberry’ at the end of the ‘test.txt’
file.
OUTPUT
Example :2
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“\nGuava”)
The above code appends the string ‘Apple’ at the end of the ‘test.txt’ file in a new
line.
output
Example :3
fruits = [“\nBanana”, “\nAvocado”, “\nFigs”, “\nMango”]
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.writelines(fruits)The above code appends a list of
data into a ‘test.txt’ file.
OUTPUT
Assignment Based on Text File
1.Write a python programs to create and read city.txt file in one go and print the
contents in the output screen
2.Write a user defined function in Python that displays the number of lines starting
with ‘H’ in the file city.txt. Example if file contains:
Whose woods these are I think know,
His house is in the village through,
He will not see me stoping here
To watch his woods fill up with snow
Then the line count should be : 2
3] Write a method Display_words() in python to read lines from a text file City.txt
and display those words which are less than 4 characters
4] Write a program to count the words “To” and ‘The’ present in text file “city.txt”
5] Write a python method to count the number of lines in a text file.
6] Write a method in Python to read lines from a text file NOTES.TXT, and count
those lines, which are ending with ‘.’ or ‘,’.
7] Write a Python method to count the no.of words in text file
Assignment Based on Text File
8.Write a function to count total no. of char and space in text file
“City.txt”
OUTPUT:
IT IS UP TO US TO TAKE CARE OF OUR
SURROUNDING. IT IS NOT POSSIBLE ONLY FOR
THE GOVERNMENT TO TAKE RESPONSIBILITY
Cursor Position : 15
TO TAKE CARE OF OUR SURROUNDING. IT IS
NOT POSSIBLE ONLY FOR THE GOVERNMENT
TO TAKE RESPONSIBILITY
tell() Functions in Python Programming
OUTPUT
Cursor Position is : 0
After reading 5 data from file
Cursor Position is : 5
RANDOM ACCESS IN FILES USING TELL() AND SEEK()
seek()—seek() function is used to change the position of the file handle (file pointer)
to a given specific position. File pointer is like a cursor, which defines from where the
data has to be read or written in the file.
For example,
f.seek(–10,1) from current position, move 10 bytes backward
f.seek(10,1) from current position, move 10 bytes forward
f.seek(–20,1) from current position, move 20 bytes backward
f.seek(10,0) from beginning of file, move 10 bytes forward
tell()—tell() returns the current position of the file read/write pointer within the file. Its
syntax is:
f.tell() #where f is file pointer
When you open a file in reading/writing mode, the file pointer rests at 0th byte.
When you open a file in append mode, the file pointer rests at the last byte.
RANDOM ACCESS IN FILES USING TELL() AND SEEK()
Concept of Relative and Absolute Paths
Relative Path: A relative path is the path that is relative to the working directory
location on your computer. In Program (oceans.py) we have used relative path of
ocean.txt in open function.
Therfore, text file 'oceans.txt' is created and stored in same folder
(current working directory) where we have saved 'oceans.py‘
Example :d:\\ test.txt is relative path.
Absolute Path: An absolute path is a path that contains the entire path to the file
that you need to access. This path will begin with drive of your computer and will
end with the file that you wish to access.
Example:C:\Users\91981\Desktop\oceans.txt
Relative and Absolute Paths
The absolute path is the full path to some place on your
computer.
The relative path is the path to some file with respect to
your current working directory (PWD).
For example:
•Absolute path: C:/users/admin/docs/staff.txt
•If PWD is C:/users/admin/
The files like images, audio files or video files are examples of
binary files.
Binary files are mainly used for storing records, just as we store
records in a database. It makes it easier to access or modify
the records easily.
Writing and Reading Data from a Binary File
Python provides the pickle module to write and read data from binary files. To work with
the pickle module, we need to import it in our program using import statement as: import
pickle
Python pickle module is used for serializing and de-serializing python object structures.
The process to converts any kind of python objects (list, dict, etc.) into byte streams (0s
and 1s) is called pickling or serialization or flattening or marshalling.
We can converts the byte stream (generated through pickling) back into python objects by
a process called as unpickling.
So when we want to work on Binary File , conversion of data at the time of reading and
writing Pickle Module is required.
PICKLE MODULE :
What is pickling?
Pickling: The process of converting the structure (lists and
dictionary etc.) into a byte stream just before writing to the file.
This is also called as object serialization.
load() function: In pickle module, load() function is used to read data from a binary
file or file object.
Syntax:
#Syntax_unpickling_in_python
import pickle
pickle.load(file)
File Mode
File Opening Modes:
wb writing only. Overwrites the binary file if exists. If
not, creates a new binary file for writing.
Example1:
f1=open("file1.txt","wb")
f3=open("file2.txt","rb")
For example, writes the record of a student (roll_no, name, gender and marks) in the
binary file named mybinary.dat using the dump().
We need to close the file after pickling
Program 2-6 Pickling data in Python import pickle
Basic Functions in Pickle Module
Ways to write data to a binary file in Python
1). Using dump() function/method
Basic Functions in Pickle Module
How to Read data from a Binary File in Python | Reading data from binary file
in Python
The load() method
This method is used to load (unpickling) data from a binary file. The file to be
loaded is opened in binary read (rb) mode.
Syntax of load() is as follows:
Store_object = load(file_object)
Here, the pickled Python object is loaded from the file having a file handle named
file_object and is stored in a new file handle called store_object.
Practical Example :3
Program to read structure , list in binary file :
OUTPUT:
Read Operation
[100, 200, 300, 400]
Binary File Based Assignment
Basic operations on a binary file :
Write or Append Operation in Binary File
Basic operations on a binary file :
READ OR DISPLAY ALL Operation in Binary File
Basic operations on a binary file :
Search Operation in Binary File
Basic operations on a binary file :
UPDATE Operation in Binary File
Basic operations on a binary file :
DELETE OR REMOVE Operation in Binary File
Practice :1
Write a code that Write the information itemcode,amout
according to user choice and then reads from a file “sales.dat”
which has following information [itemcode, amount] display
each record and last find out the the sum of the amount.
Update record in Binary file
• To update record follow these steps: def update():
• Open the file using read mode f = open("Sports.dat","rb+")
• Open another file for a write operation pc = int(input("Player to code to search”))
• Declare a variable for unique value to be tf = 0
updated data= pickle.load(f)
• Place the cursor at the beginning, use seek(0) for record in data:
function to do so if record[0]==pc:
• Use try-except and while loop as explained
record[1]=input("Enter Player Name to
above
• Find the current position of the cursor using
update:")
tell() function record[2]=input("Enter Individual
• Use the same logic as done in search record Score to update:")
and ask values to be update record[3]= input("Enter score to
• Now again place the cursor at current position update:")
using seek() function tf = 1
• Write the data using dump() function break
• remove the old file using remove() function
• rename the temp file with the original file if tf==1:
• Use read logic to check the updated records f.seek(0)
pickle.dump(data,f)
print("Record is updated...")
f.close()
Delete the record
Let’s have look at these steps: def bf_delete():
• Open the file in reading mode f = open("Sports.dat","rb")
• Load data using the load function
data=pickle.load(f)
• Close file f.close()
• Prompt a message to delete a record pc = int(input("Player to code to
with a variable delete a record:"))
• Open file in writing mode f = open("Sports.dat","wb")
• Declare a list object to store data from lst=[ ]
the file for record in data:
• Use for loop and if condition as used in if record[0]==pc:
the update and delete, try-except is not continue
necessary lst.append(record)
• Now in if condition write continue if the pickle.dump(lst,f)
record is found f.close()
• Now append the data into a list object
• Write data using the dump method
• Close the file and read data again
What is an Absolute Path?
An absolute path is a path that describes the
location of a file or folder regardless of the
current working directory; in fact, it is relative to
the root directory. It contains the complete
location of a file or directory, hence the name.
Example:
>>> import os
>>> cwd=os.getcwd()
>>> print(cwd)
C:\Users\INDIAN\AppData\Local\Programs\Python\Python37-32
>>>
Standard input, output, and error streams in python
CSV Data
•Programming language, Designed by, Appeared, Extension
•Python, Guido van Rossum, 1991, .py
•Java, James Gosling, 1995, .java
•C++, Bjarne Stroustrup, 1983, . cpp
As you can see each row is a new line, and each column is separated with a comma.
This is an example of how a CSV file looks like.
Opening csv file:
syntax:
fh=open(“stu.csv”,”w”)- to open the file in write mode
fh=open(“stu.csv”,”r”)- to open the file in read mode
Python CSV Module
• 2.
writerobject.writerow() – writes one row of data onto the
writer object
example : stuwriter.writerow(sturec) #sturec=[23,’Rustom’,79]
• 3.
writerobject.writerows()- writes multiple rows of data onto
the writer
example : stuwriter.writerows(sturec) #
sturec=[[11,’Nishtha’,99],[12,’Rudy’,’89.0]]
CSV File Writer Example -1
CSV File Writer Example -2
OUTPUT:
['SN,Name,Contribution']
['1,Linus', 'Torvalds,Linux', 'Kernel']
['2,Tim', 'Berners-Lee,World', 'Wide', 'Web']
['3,Guido', 'van', 'Rossum,Python', 'Programming']
How to write/read CSV File with optional argument
OUTPUT
•Writing CSV files with DictWriter()
DictWriter()
This function returns a DictWriter object. It is
similar to writer object, but the rows are mapped
to dictionary object.
The function needs a file object with write
permission and a list of keys used in dictionary
as fieldnames parameter. This is used to write
first line in the file as header.
The DictWriter object writes a dictionary to a CSV
file. Its syntax is as follows:
Method Description
writeheader() Writes the header (i.e fieldnames) to the CSV
file and returns None.
writerow(row) Writes a single row of data and returns the
number of characters written. The row must be
a sequence of strings and number.
writerows(rows) Writes multiple rows of data and
returns None. The rows must be a sequence.
•Example 1:T0 Write Dictionary in CSV file
•Example 2 :T0 Write Dictionary in CSV file
•How to Read a CSV as a Dictionary
You can also you use DictReader to read CSV files.
The results are interpreted as a dictionary where the
header row is the key, and other rows are values.
OUTPUT:
OrderedDict([('id', '1'), ('name', 'Hannah'), ('address', '4891 Blackwell Street')])
OrderedDict([('id', '2'), ('name', 'Walton'), ('address', '4223 Half and Half Drive')])
OrderedDict([('id', '3'), ('name', 'Sam'), ('address', '3952 Little Street, Akron, Ohio')])
OrderedDict([('id', '4'), ('name', 'Chris'), ('address', '3192 Flinderation Road')])
OrderedDict([('id', '5'), ('name', 'Doug'), ('address', '3236 Walkers Ridge Way')])
•How to Write/Read from CSV as a Dictionary
OUTPUT
Short Revision
End of the chapter