Study Material File Handling

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 1

Duration
Date Category Timing Topics
(Minutes)
Revision 80 4:10 - 5:30 File handling - Text File
29/09/23
90 7:00 - 8:30 Text File Practice Sheet
Friday Home Study
30 9:00 - 9:30 Text File Revision
Revision 60 7:40 - 8:40 File handling - Binary File
Revision 50 9:10 - 10:00 File handling - Binary File
Revision 50 10:00 - 10:50 File handling - CSV File
30/09/23
Revision 100 11:00 - 12:40 File handling - CSV File
Saturday
1:20 - 2:50 &
Practice 140 Practice Sheet - Binary File
3:00 - 3:50
Practice 90 4:00 - 5:30 Practice Sheet - CSV File
Home Study 90 7:00 - 8:30 Binary File Revision
01/10/23 150 10:00 - 12:30 Binary File Revision
Home Study
Sunday 150 5:00 - 7:30 Text File Revision
02/10/23 150 10:00 - 12:30 CSV File Revision
Home Study
Monday 150 5:00 - 7:30 Text, Binary and CSV File Revision
Discussion 60 7:40 - 8:40 Doubt Clarification
Test 100 9:10 - 10:50 Revision Test 1 - File Handling
Revision 100 11:00 - 12:40 Computer Networks 1 Mark Ques
03/10/23 Revision 90 1:20 - 2:50 Computer Networks 2 Mark Ques
Tuesday Revision 50 3:00 - 3:50 Computer Networks 5 Mark Ques
Practice 90 4:00 - 5:30 Computer Networks Practice Sheet
90 7:00 - 8:30 Computer Networks Practice Sheet
Home Study
30 9:00 - 9:30 Computer Network Revision
04/10/23 Discussion 60 7:40 - 8:40 Doubt Clarification
Wednes Test 100 9:10 - 10:50 Revision Test 2 - FH & CN
day Discussion 60 11:00 - 12:00 Doubt Clarification
Category Total (Minutes)
Revision 580 - 9 Hours 40 Min
Home Study 930 - 15 Hours 30 Min
Practice 320 - 5 Hours 20 Min
Test 200 - 3 Hours 20 Min
Discussion 180 - 3 Hours

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 2
File handling

A file is a named location on a secondary storage media where data are permanently stored for
later access.

TYPES OF FILES
Computers store every file as a collection of 0s and 1s i.e., in binary form
There are mainly two types of data files — text file and binary file.

A text file consists of human readable characters, which can be opened by any text editor.
A Binary files are made up of non-human readable characters and symbols, which require specific
programs to access its contents.

Text file
A text file can be understood as a sequence of characters consisting of alphabets, numbers and
other special symbols.
Files with extensions like .txt, .py, .csv, etc. are some examples of text files.
Each line of a text file is terminated by a special character, called the End of Line (EOL).
Contents in a text file are usually separated by whitespace, but comma (,) and tab (\t) are also
commonly used to separate values in a text file.

In real world applications, computer programs deal with data coming from different sources like
databases, CSV files, HTML, XML, JSON, etc. We broadly access files either to write or read data
from it. But operations on files include creating and opening a file, writing data in a file,
traversing a file, reading data from a file and so on. Python has the io module that contains
different functions for handling files.

Opening a file
To open a file in Python, we use the open() function. The syntax of open() is as follows:

file_object= open(file_name, access_mode)

Here are parameter details:


file_name: The file_name argument is a string value that contains the name of the file that
you want to access.
access_mode: The access_mode determines the mode in which the file has to be opened,

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 3
i.e., read, write, append, etc. This is optional parameter and the default file access mode is
read (r).

Closing a file
Once we are done with the read/write operations on a file, it is a good practice to close the file.
Python provides a close() method to do so. While closing a file, the system frees the memory
allocated to it.

file_object.close()
Opening a file using with clause

with open (file_name, access_mode) as file_ object:

The advantage of using with clause is that any file that is opened using this clause is closed
automatically

Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning
of the file. This is the default mode
rb Opens a file for reading only in binary format. The file pointer is placed
at the beginning of the file. This is the default mode
r+ Opens a file for both reading and writing. The file pointer is placed at
the beginning of the file
rb+ Opens a file for both reading and writing in binary format. The file
pointer is placed at the beginning of the file
w Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing
wb Opens a file for writing only in binary format. Overwrites the file if the
file exists. If the file does not exist, creates a new file for writing
w+ Opens a file for both writing and reading. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and
writing
wb+ Opens a file for both writing and reading in binary format. Overwrites
the existing file if the file exists. If the file does not exist, creates a new
file for reading and writing
a Opens a file for appending. The file pointer is at the end of the file if the

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 4
file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing
ab Opens a file for appending in binary format. The file pointer is at the
end of the file if the file exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for writing
a+ Opens a file for both appending and reading. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing
ab+ Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for reading
and writing.

READING FROM A TEXT FILE


We can write a program to read the contents of a file.
Before reading a file, we must make sure that the file is opened in “r”, “r+”, “w+” or “a+” mode.
There are three ways to read the contents of a file:
The read() method
This method is used to read a specified number of bytes of data from a data file.
The syntax of read() method is

file_object.read(n)

The readline([n]) method


This method reads one complete line from a file where each line terminates with a newline (\n)
character.
It can also be used to read a specified number (n) of bytes of data from a file but maximum up to
the newline character (\n).

To read the entire file line by line using the readline(), we can use a loop.
This process is known as looping/ iterating over a file object.
It returns an empty string when EOF is reached.

The readlines() method


The method reads all the lines and returns the lines along with newline as a list of strings.

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 5
Example Program

sample.txt
Python provides basic functions and methods necessary to manipulate files by default. You can
do your most of the file manipulation using a file object

# to Read the Contents of a File


first = open('sample.txt')
print(first.read())

Output:
Python provides basic functions and methods necessary to manipulate files by default. You can
do your most of the file manipulation using a file object

# to Read the Contents of a File in Reverse Order


filename=input("Enter file name: ")
for line in reversed(list(open(filename))):
print(line.rstrip())

Output:
Enter file name: sample.txt
default. You can do your most of the file manipulation using a file object
Python provides basic functions and methods necessary to manipulate files by

# to Count the Number of Lines in a Text File


fname = input("Enter file name: ")
num_lines = 0
with open(fname, 'r') as f:
for line in f:
num_lines += 1
print("Number of lines:", (num_lines))

Output:
Enter file name: sample.txt
Number of lines: 3

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 6

# Another Method - to Count the Number of Lines in a Text File


num_lines = 0
with open('sample.txt', 'r') as f:
for line in f:
num_lines += 1
print("Number of lines:", (num_lines))

Output:
Number of lines: 3

sample.txt
Anbu is a Doctor
Ram is a Civil Engineer
Rakesh is a Architect
Ram is a Teacher
Anitha is a Enterprenurship
Ambika is a Software Engineer

# to Count the Occurrences of a Word in a Text File


fname = input("Enter file name: ")
word=input("Enter word to be searched:")
count = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
count += 1
print("Occurrences of the word:",(count))

Output:
Enter file name: sample.txt
Enter word to be searched:Ram
Occurrences of the word: 2

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 7
Enter file name: sample.txt
Enter word to be searched:is
Occurrences of the word: 6

# Another Method - to Count the Occurrences of a Word in a Text File


word=input("Enter word to be searched:")
count = 0
with open('sample.txt') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
count += 1
print("Occurrences of the word:",(count))

Output:
Enter word to be searched:a
Occurrences of the word: 6

sample.txt
Anbu is a Doctor
Ram is a Civil Engineer
Rakesh is a Architect
Ram is a Teacher
Anitha is a Enterprenurship
Ambika is a Software Engineer

# to Copy the Contents of One File into Another


with open("sample.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)

Output:
out.txt
Anbu is a Doctor

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 8
Ram is a Civil Engineer
Rakesh is a Architect
Ram is a Teacher
Anitha is a Enterprenurship
Ambika is a Software Engineer

#to Append the Contents of One File to Another File


name1 = input("Enter file to be read from: ")
name2 = input("Enter file to be appended to: ")
fin = open(name1, "r")
data2 = fin.read()
fin.close()
fout = open(name2, "a")
fout.write(data2)
fout.close()

Output:
Enter file to be read from: sample.txt
Enter file to be appended to: test.txt
test.txt
Anbu is a Doctor
Ram is a Civil Engineer
Rakesh is a Architect
Ram is a Teacher
Anitha is a Enterprenurship
Ambika is a Software Engineer

WRITING TO A TEXT FILE

For writing to a file, we first need to open it in write or append mode. If we open an existing file
in write mode, the previous data will be erased, and the file object will
be positioned at the beginning of the file. On the other hand, in append mode, new data will be
added at the end of the previous data as the file object is at the end of the file. After opening the
file, we can use the following methods to write data in the file.

write() - for writing a single string

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 9
writelines() - for writing a sequence of strings

The write() method

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.

Also, we need to add a newline character (\n) at the end of every sentence to mark the end of line.

fileObject.write(string)

The writelines() method

to write multiple strings to a file. We need to pass an iterable object like lists, tuple, etc.
containing strings to the writelines() method.

SETTING OFFSETS IN A FILE

The functions that we have learnt till now are used to access the data sequentially from a file.
But if we want to access data in a random fashion, then Python gives us seek() and tell() functions
to do so

The tell() method


This function returns an integer that specifies the current position of the file object in the file.
The position so specified is the byte position from the beginning of the file till the current position
of the file object.
The syntax of using tell() is:

File_object.tell()

The seek() method


This method is used to position the file object at a particular position in a file. The syntax of seek()
is:
file_object.seek(offset [, reference_point])

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 10
offset is the number of bytes by which the file object is to be moved. reference_point
indicates the starting position of the file object

It can have any of the following values:

0 - beginning of the file


1 - current position of the file
2 - end of file
By default, the value of reference_point is 0, i.e. the offset is counted from the beginning of the file

Practice Programs

Q.No Questions Marks


Write a user-defined function named Count() that will read the contents of
text file named “Report.txt” and count the number of lines which starts with
either „I‟ or „M‟. E.g. In the following paragraph, there are 2 lines starting
with „I‟ or „M‟:
“India is the fastest growing economy.
India is looking for more investments around the globe.
The whole world is looking at India as a great market.
Most of the Indians can foresee the heights that India is capable of reaching.”
A text file “Quotes .Txt” has the following data written in it:
Living a life you can be proud of
Doing your best
Spending your time with people and activities that are important to you
Standing up for things that are right even when it’s hard
Becoming the best version of you
Write a user defined function to display the total number of words present in
the file.
Write a function in Python to count the number of lines in a text file
‘STORY.TXT’
which is starting with an alphabet ‘A’.
Write a function in python to count the number lines in a text file
‘Country.txt’which is starting with an alphabet ‘W’ or ‘H’. If the file
contents are as follows:
Whose woods these are I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.
The output of the function should be:
W or w : 1
H or h : 2
Write a user defined function countwords( ) to display the total number of

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 11
words present inthe text file “Quotes.Txt”. If the text file has the following
data written in it:
Living a life you can be proud of doing your best
Spending your time withpeople and activities that are important to you
Standing up for things that areright even when it’s hard
Becoming the best version of you
The countwords() function should display the output as:
Total number of words : 40
Write a method in python to write multiple line of text contents into a text
file mylife.txt
Write a method in Python to read lines from a text file INDIA.TXT, to find
and display the occurrence of the word 'India'. For example, if the content of
the file is:
India is the fastest-growing economy. India is looking for more investments
around the globe. The whole world is looking at India as great market. Most
of the Indians can foresee the heights that India is capable of reaching.
The output should be 4.
Write a function show_word() in python to read the contant of a text file
'words.txt' and display the entire content in upper case.example,if the file
contain
"I love my country ,i am proud to be indian"
Then the function should display the output as:
I LOVE MY COUNTRY ,I AM PROUD TO BE INDIAN
Write a function mycount() in python to read the text file 'file.txt' and count
the number of times "i" occurs in the file. example,if the file is
'file.txt'contains:
"I love my country ,i am proud to be indian"
The mycount()function should display the output as:
"i occurs 4 times"
Write a Python function which reads a text file “poem.txt” and prints the
number of vowels in each line of that file, separately.
Eg: if the content of the file “poem.txt” is
The plates will still shift
and the clouds will still spew.
The sun will slowly rise
and the moon will follow too.
The output should be
6
7
6
9
Write a Python program that writes the reverse of each line in “input.txt”
to another text file “output.txt”. Eg: if the content of input.txt is:
The plates will still shift
and the clouds will still spew.

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 12
The sun will slowly rise
and the moon will follow too.
The content of “output.txt” should be:
tfihs llits lliw setalp ehT
.weps llits lliw sduolc eht dna
esir ylwols lliw nus ehT
.oot wollof lliw noom eht dna
Write a function named COUNT_CHAR() in python to count and display
number of times the arithmetic operators(+,-,*,/) appears in the file
“Math.txt” .
Example:
Solve the following:
1.(A+B)*C/D
2.(A-B)*(A+B)/D-(E/F)
3. A+B+C/D*(E/F)
The function COUNT_CHAR() must display the output as
Number of ‘+’ sign is 4
Number of ‘-‘ sign is 2
Number of ‘*’ sign is 3
Number of ‘/’ sign is 5
Write a function V_COUNT() to read each line from the text file and count
number of lines begins and ends with any vowel
Example:
Eshwar returned from office and had a cup of tea.
Veena and Vinu were good friends.
Anusha lost her cycle.
Arise! Awake! Shine.
The function must give the output as:
Number of Lines begins and ends with a vowel is 3
Write a function Show_words( ) in python to read the content of a text file
‘NOTES.TXT” and display the entire content in capital letters. Example if the
file contains:
“This is a test file”
Then the function should display the output as:
THIS IS A TEST FILE
Write a function countmy( ) in python to read the text file “DATA.TXT”
and count the number of times “my” occurs in the file.
For example if the file “DATA.TXT” contains:
“This is my website. I have displayed my preferences in the CHOICE
section” The countmy( ) function should display the output as : “my occurs 2
times”
Write a function in Python that counts the number of “Me” or “My”
words present in a text file “STORY.TXT”. If the “STORY.TXT” contents are
as follows:
My first book was Me and My family.

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 13
It gave me chance to be known to the world.
The output of the function should be:
Count of Me/My in file:
Write a function/method DISPLAYWORDS( ) in python to read lines from a
text file STORY.TXT and display those words, which are less than 4
characters.
Write a function to count the words He/She in a file
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
Write a function countdigits() in Python, which should read each character of
a text file “marks.txt”, count the number of digits and display the file content
and the number of digits.
Example: If the “marks.txt” contents are as follows:
Harikaran:40,Atheeswaran:35,Dahrshini:30,Jahnavi:48
Write a function in python to count number of words ending with ‘n’ present
in a text file “ABC.txt”
If ABC.txt contains “A story of a rich man And his son”, the output of the
function should be Count of words ending with ‘n’ is 2
A text file contains alphanumeric text (say an.txt).Write a program that reads
this text file and prints only the numbers or digits from the file.
Write a function COUNTTEXT( ), which reads a text file Book.txt and
displays all the words of the file whose length is more than 3 or those which
start with ‘A’ or ‘a’ in the form of a list.
For example, if the Book.txt file contains
India is my country. They are studying.
then the output should be:
[“India”, “country”, “They”, “are”, “studying”]
Write a function in Python to print those words which contains letter ‘S’ or ‘s’
anywhere in the word in text file “STORY.txt”.
If the “STORY.txt” contents are as follows:
An Old Man is happy today, he doesn’t complain about anything, smiles,
and even his face is freshened up. The output of the function should be: is
doesn’t smiles his is freshened
Write a function WordCount() in Python to read a text file “Mydiary.txt” and
display no of words present in each line.
Example:
If the file content is as follows:
Updated information
As simplified by official websites.
The function should display the output as:
Line No 1 : Words=2
Line No 2 : Words=5
Write a method/function COUNTLINES_ET() in python to read lines from a
text file

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti
COMPUTER SCIENCE BOARD REVISION - AY 2023 - 24 14
REPORT.TXT, and COUNT those lines which are starting either with ‘E’ or
starting
with ‘T’ and display the Total count separately.
For example:
If REPORT.TXT consists of
“ENTRY LEVEL OF PROGRAMMING CAN BE LEARNED FROM PYTHON.
ALSO, IT
IS VERY FLEXIBLE LANGUGAE. THIS WILL BE USEFUL FOR VARIETY OF
USERS.”
Then, Output will be:
No. of Lines with E: 1
No. of Lines with T: 1
Write a function countwords() in Python that counts the number of words
containing digits in it
present in a text file “myfile.txt”.
Example: If the “myfile.txt” contents are as follows:
This is my 1st class on Computer Science. There are 100 years in a Century.
Student1 is present in
the front of the line.
The output of the function should be: 3
Write a function countVowels() in Python, which should read each character
of a
text file “myfile.txt”, count the number of vowels and display the count.
Example: If the “myfile.txt” contents are as follows:
This is my first class on Computer Science.
The output of the function should be: Count of vowels in file: 10
Write a function countmy( )in Python to read the text file “Story.txt” and
count the number of times “my” or “My” occurs in the file. For example if
the file “Story.TXT” contains:
“This is my website. I have displayed my preferences in the CHOICE
section.”
The countmy( ) function should display the output as: “my occurs 2 times”

Prepared by Dr. Dhanasekaran.S, Head - Technical Enrichment and Project Development, Vel’s Vidhyalaya Kovilpatti

You might also like