0% found this document useful (0 votes)
32 views9 pages

Data File Handling Text File

The document provides an overview of data file handling in Python, detailing text files, binary files, and CSV files, along with various file operations such as reading, writing, and appending data. It explains functions like open(), close(), read(), write(), and seek(), as well as the modes to open files. Additionally, it includes practical examples and exercises to reinforce the concepts of file handling in Python.

Uploaded by

dhruvsuyal57
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views9 pages

Data File Handling Text File

The document provides an overview of data file handling in Python, detailing text files, binary files, and CSV files, along with various file operations such as reading, writing, and appending data. It explains functions like open(), close(), read(), write(), and seek(), as well as the modes to open files. Additionally, it includes practical examples and exercises to reinforce the concepts of file handling in Python.

Uploaded by

dhruvsuyal57
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 9

DOON INTERNATIONAL SCHOOL

CITY CAMPUS,
DALANWALA, DEHRADUN

DATA FILE HANDLING ( TEXT FILE)


Text File – A text file is one whose contents may be examined using a text
editor. Simply put, a text file is a collection of ASCII or Unicode characters.
Text files include things like Python programmes and content created in text
editors.
Binary File – A binary file is one whose content is stored in the form of binary,
which consists of a series of bytes, each of which is eight bits long. Word
documents, MP3 files, picture files, and .exe files are a few example of
binary files.
CSV (Comma Separated Values) Files: It is a plain text file that contains a
list of data. CSV files can be opened and operated by MS Excel and allow to
export and import data. It can handle big data. All the values are separated
by a comma.
open(): this function is used to open a data file.
close(): function breaks the link of the file object and the file on the disk .
read() : Returns the read bytes in form of a string.
read(n) Reads n bytes, if no n specified, reads the entire file.
readline() : Reads a line of the file and returns in form of a string. For
specified n, reads at most n bytes. However, does not reads
more than one line, even if n exceeds the length of the line.
readlines() : Reads all the lines and return them as each line a string
element in a list.
write(): The write() method writes a string to a text file .

writelines() :The writelines() method write a list of strings to a file at once.

With : Apart from using open() function for creation of file, with statement
can also be used for the same purpose. We can use this statement to group
file operation statements within block to make the code compact and much
more readable. We are required to close the file explicitly using wit
statement.

The os module provides functions for working with files and directories OS
stand for operating system.

os.getcwd() returns the name for the current directory.

imprt os

ns=os.cwd()

print(ns)

1
NARENDRA SRIVASTAVA , DOON INTERNATIONAL SCHOOL DEHRADUN
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

This program will print current directory.

sys.stdin When a stream reds from standard input

sys.stdout Data written to sys.stdout typically appears on screen, but can

be linked to the standard input of another program with a pipe.

sys.stderr error message are written to sys,stderr.

seek() method
In Python, seek() function is used to change the position of the File
Handle to a given specific position. File handle is like a cursor, which defines
from where the data has to be read or written in the file.
The reference point is selected by the from_what argument. It accepts three
values:

 0: sets the reference point at the beginning of the file

 1: sets the reference point at the current file position

 2: sets the reference point at the end of the file

By default from_what argument is set to 0.


Ns.seek(-10,1) move 10 bytes backward from current position
Ns. seek(10,1) move 10 bytes forward from current position
Ns. seek(10,0) move 10 bytes forward from beginning of file

Note: Reference point at current position / end of file cannot be set in text
mode except when offset is equal to 0.

tell():The tell() method returns the current file position in a file stream.

What is the difference between tell() and seek in Python?


tell () function in Python is used to find the current position of the file pointer from the
beginning in the given file. seek () function in Python is used to bring the file pointer
to the given specified position. offset: It represents how many bytes to move.
position: It represents from which position file pointer should move.

2
NARENDRA SRIVASTAVA , DOON INTERNATIONAL SCHOOL DEHRADUN
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

MODES TO OPEN A FILE

Access
Modes Description
r Opens a file for reading only.
rb Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in binary format.
w Opens a file for writing only.
wb Opens a file for writing only in binary format.
w+ Opens a file for both writing and reading.
wb+ Opens a file for both writing and reading in binary format.
a Opens a file for appending.
ab Opens a file for appending in binary format.
a+ Opens a file for both appending and reading.
ab+ Opens a file for both appending and reading in binary format.

Data file operations


The following tasks will be performed on data files.
1. Creation of files
2. Opening files
3. Reading files
4. Writing files
5. Appending data in files
6. Deleting Data from files
7. Creating copy
8. Updating files data

Fill in the blanks


1. A collection of bytes stored in computer’s secondary memory is known as _______.
2. ___________ is a process of storing data into files and allows to performs various
tasks such as read, write, append, search and modify in files.
3. The transfer of data from program to memory (RAM) to permanent storage device
(hard disk) and vice versa are known as __________.
4. A _______ is a file that stores data in a specific format on secondary storage
devices.
5. In ___________ files each line terminates with EOL or ‘\n’ or carriage return, or ‘\r\n’.
6. To open file data.txt for reading, open function will be written as f = _______.
7. To open file data.txt for writing, open function will be written as f = ________.

3
NARENDRA SRIVASTAVA , DOON INTERNATIONAL SCHOOL DEHRADUN
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

8. In f=open(“data.txt”,”w”), f refers to ________.


9. To close file in a program _______ function is used.
10. A __________ function reads first 15 characters of file.
11. A _________ function reads most n bytes and returns the read bytes in the form of a
string.
12. A _________ function reads all lines from the file.
13. A _______ function requires a string (File_Path) as parameter to write in the file.
14. A _____ function requires a sequence of lines, lists, tuples etc. to write data into file.
15. To add data into an existing file ________ mode is used.
16. A _________ function is used to write contents of buffer onto storage.
17. A text file stores data in _________ or _________ form.
18. A ___________ is plain text file which contains list of data in tabular form.
19. You can create a file using _________ function in python.
20. A __________ symbol is used to perform reading as well as writing on files in python.

Find answer below for data file handling in python class 12.

Answers:
1. File
2. File Handling
3. I/O Operations
4. Data file
5. Text File
6. open(“data.txt”,”r”)
7. open(“data.txt”,”w”)
8. File handle or File Object
9. close
10. read(15)
11. readline()
12. readlines()
13. write()
14. writelines()
15. append
16. flush()

4
NARENDRA SRIVASTAVA , DOON INTERNATIONAL SCHOOL DEHRADUN
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

17. ASCII, UNICODE


18. CSV
19. open()
20. +

Differentiate between the following:


(i) f = open ('diary. txt', 'r')
(ii) f = open ('diary. txt', 'w')
Ans.
(i) diary.txt is opened for reading data (ii) diary.txt is opened for writing data

Write a method in python to read the content from a text file diary.txt line by line and
display the same on screen.
Ans.
def read_file():
ns = open('diary.txt', 'r')
for line in ns:
print (line)
ns.close()
Observe the following code and answer the questions that follow: File =
open("Mydata","a") _____________________ #Blank1 File.close() i.
What type (Text/Binary) of file is Mydata? ii. Fill the Blank 1 with
statement to write “ABC” in the file “Mydata”
Ans.
i. Text File
ii. ii. File.write("ABC")

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.
def DIS():
ns=open("mydata.txt","r")
a=ns.read()
b=a.split()
print("Total Words in the file=",len(b))
ns.close()

5
NARENDRA SRIVASTAVA , DOON INTERNATIONAL SCHOOL DEHRADUN
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

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”.
def countmy():
ns=open("data.txt","r")
a=ns.read()
b=a.split()
count=0
for i in b:
if i=="my":
count=count+1
print("my in the file=",count)
ns.close()

Differentiate between “w” and “r” file modes used in Python while opening
a data file. Illustrate the difference using suitable examples
A file is opened using “w” mode to write content into the file. A file is
opened using “r” mode to read content into the file. Example:
def Create():
file=open('NOTES.TXT','w')
S="This is a sample" file.write(S)
file.close()
def Read():
file=open('NOTES.TXT','r')
Lines=file.readline();
print(Lines)
file.close()
Create();
Read();

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
def Show_words():
file=open('NOTES.TXT','r')
Lines = file.readlines()

6
NARENDRA SRIVASTAVA , DOON INTERNATIONAL SCHOOL DEHRADUN
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

for L in Lines:
print(L.upper())
file.close()

Write a function Show_words() in python to read the content of a text file


'NOTES.TXT' and display only such lines of the file which have exactly 5
words in them. Example, if the file contains: "This is a sample file. The
file contains many sentences. But need only sentences which have only
5 words." Then the function should display the output as: This is a
sample file.
def Show_words():
file=open('NOTES.TXT','r')
Lines = file.readlines()
for L in Lines:
W=L.split()
if (len(W)==5):
print(L)
file.close()
Write a statement in Python to open a text file WRITEUP.TXT so that
new content can be written in it
file= open("WRITEUP.TXT","w")
OR
file= open("WRITEUP.TXT","w+")

Write a statement in Python to open a text file README.TXT so that


existing content can be read from it.
file= open("README.TXT","r")
OR
file= open("README.TXT","r+")

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”. For example: If the content of the file is “
IT IS UP TO US TO TAKE CARE OF OUR SURROUNDING. IT IS NOT
POSSIBLE ONLY FOR THE GOVERNMENT TO TAKE
RESPONSIBILITY “
The method/function should display Count of IS TO and UP is 6
def ISTOUPCOUNT():
c=0
file=open('WRITER.TXT','r')
line = file.read()
7
NARENDRA SRIVASTAVA , DOON INTERNATIONAL SCHOOL DEHRADUN
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

word = line.split()
for w in word:
if w=="IS" or w=="TO" or w=="UP":
c=c+1
print( "Count of IS TO and UP is ",c)
file.close()

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. For example: If the content of the file is
“A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD
HEALTH. WE SHOULD TAKE CARE OF OUR ENVIRONMENT.
EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD. The
method should display A CLEAN ENVIRONMENT IS NECESSARY FOR
OUR GOOD HEALTH. EDUCATIONAL INSTITUTIONS SHOULD TAKE
THE LEAD.”
def AEDISP():
file=open('WRITER.TXT','r')
lines = file.readlines()
for w in lines:
if w[0]=="A" or w[0]=="E":
print (w)
file.close()

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
Ans.
def Show_words():
file=open('NOTES.TXT','r')
Lines = file.readlines()
for L in Lines:
print(L.upper())
file.close()

Write a function Show_words() in python to read the content of a text file


'NOTES.TXT' and display only such lines of the file which have exactly 5
words in them.
8
NARENDRA SRIVASTAVA , DOON INTERNATIONAL SCHOOL DEHRADUN
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN

Example, if the file contains:


"This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words."
Then the function should display the output as:
This is a sample file.
The file contains many sentences.
Ans
def Show_words():
file=open('NOTES.TXT','r')
Lines = file.readlines()
for L in Lines:
W=L.split()
if (len(W)==5):
print(L)
file.close()

9
NARENDRA SRIVASTAVA , DOON INTERNATIONAL SCHOOL DEHRADUN

You might also like