0% found this document useful (0 votes)
36 views51 pages

08 - Python Data Files 1 XII - CS - 2025-2026

Uploaded by

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

08 - Python Data Files 1 XII - CS - 2025-2026

Uploaded by

ps4861251
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer Science

CLASS-XII (Code No. 083)

DPS RKP Computer Science Department


Python Data Files

2025-2026
Unit 1: Computational Thinking and Programming - 2
● Introduction to files, types of files (Text file, Binary file, CSV file), relative and
absolute paths
● Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing
a text file, opening a file using with clause, writing/appending data to a text

DPS RKP Computer Science Department


file using write() and writelines(), reading from a text file using read(),
readline() and readlines(), seek and tell methods, manipulation of data in a
text file

2
Data Files
Till now, you have been storing data in Variables, which had life span of one
execution time only.

If you have created a list/dictionary with 100 values entered by user for

DPS RKP Computer Science Department


performing certain operations. Now, you can very well understand that the data
entered by the user will completely get lost as soon as the execution over as is
stored in a variable (RAM).

And so, we require Data Files. In Python, we will learn to create three types of
Data Files
● Text .txt
● CSV .csv
● Binary .dat
3
Text File
Text File: It is a Data File, which contains sequence of characters. It can be saved
in any storage device and read from any Text Editor like NotePad. Text file is also
known as Flat File.
VIEW FROM

DPS RKP Computer Science Department


NOTEPAD
STORY.TXT
Those of us who love
short stories know the
magic behind a well-told
tale. There are times
whelete story with a
beginning, a middle, and
an end.n you just need a
comp
4
Flow of Control - Code to Write on Text File

STORY.PY STORY.TXT
# Python Code to Those of us who love

DPS RKP Computer Science Department


# Write content short stories know the
# on Text File magic behind a well-told
tale. There are times
when you just need a
complete story with a
beginning, a middle, and
an end.

5
Flow of Control - Code to Read from Text File

STORY.TXT STORY.PY
Those of us who love # Python Code to

DPS RKP Computer Science Department


short stories know the # read content
magic behind a well-told # from a Text File
tale. There are times
when you just need a
complete story with a
beginning, a middle, and
an end.

6
Opening and closing text files [Alternate 1]
Opening a text file

<File Object>=open(<FileName>,<Mode>) r - read


w - write
<File operation Statements>

DPS RKP Computer Science Department


a - append
Closing a data file
<File Object>.close()

F=open("STORY.TXT","r")
Lines=F.readlines()
F=open("C:/MyProject/STORY.TXT","r")
print(Lines)
F.close()

7
Opening and closing text files [Alternate 2]
Opening and closing text file

with open(<FileName>,<Mode>) as <FileObject>: r - read


w - write
<File operation Statements>

DPS RKP Computer Science Department


a - append

with open("STORY.TXT","r") as F:
Lines=F.readlines()
print(Lines)

Note: In the Alternative 2, closing of file (F.close()) is not required as it will close
automatically when the control will move out of the indented block of code.

8
File Modes

r Read Mode - To read the content from an existing Text File. Raises
exception FileNotFoundError, if the file does not exist

DPS RKP Computer Science Department


w Write Mode - To allow user to write the content on a new Text
File. If the file already exists it will be overwritten.

a Append Mode - To allow user to write the content on an existing


Text File. If the file does not exist, it will create a new one.

9
Flow of Writing/Appending the Text in the File
F.write(TXT+"\n")
F SAMPLE.TXT
Hello Friends

DPS RKP Computer Science Department


How are you?
Thank You!

USER Thank You!


TXT

OR
TXT=["Hello Friends\n","How are you?\n", "Thank You!\n"]
F.writelines(TXT) 10
Flow of Reading the content from a Text File
TXT
SAMPLE.TXT F
Hello Friends
Hello Friends How are you?
How are you? Thank You!

DPS RKP Computer Science Department


Thank You! TXT=F.read()
OR TXT
TXT=F.readline() Hello Friends
OR
USER
TXT=F.readlines()

TXT
['Hello Friends\n','How are you?\n','Thank You!\n']
11
Use of read() method to read content from file
read() reads all characters from the beginning to end alongwith escape
sequence of characters like newline character from the standard input
stream. Size is optional, it specifies number of characters.

DPS RKP Computer Science Department


with open("STORY.TXT") as f:
READs the entire content of File
L=f.read()
print(L)
Those of us who love
short stories know the
magic behind a well-told
tale.

12
Use of read() method to read content from file
read(<size>) reads the next characters from the standard input stream.
(Size is optional), it specifies number of characters.

with open("STORY.TXT") as f:

DPS RKP Computer Science Department


READs first five characters from File
L=f.read(5)
print(L)
L=f.read(6) READs next six characters from File
print(L)
Those
of us

13
Use of readline() method to read content from file
readline() reads the next line of characters from the standard input stream.

with open("STORY.TXT") as f: READs first line of characters from File

DPS RKP Computer Science Department


L=f.readline()
print(L) READs next line of characters from File
L=f.readline()
print(L) Those of us who love

short stories know the

14
Use of readlines() method to read content from file
readlines() returns a list containing all the lines in the file

with open("STORY.TXT") as f:
READs list of line from File
L=f.readlines()

DPS RKP Computer Science Department


print(L)

['Those of us who love\n', 'short stories know the\n', 'magic


behind a well-told\n', 'tale.\n' ]

15
Reading content with Exception handler [Alt-1]
try:
f=open("STORY.TXT","r") Output of the code,
for i in range(1,5): when file exists
L=f.read(i);print(L)

DPS RKP Computer Science Department


f.close() T
except FileNotFoundError: ho
print("File Not Found") se
of u

File Not Found

Output of the code,


when file does not exists
16
Reading content with Exception handler [Alt-2]
try:
Output of the code,
with open("STORY.TXT","r") as f:
when file exists
for i in range(1,5):
L=f.read(i);print(L)

DPS RKP Computer Science Department


except FileNotFoundError: T
print("File Not Found") ho
se
of u

File Not Found

Output of the code,


when file does not exist
17
Creation of a New Text File by taking user input
with open("STORY.TXT","w") as f:
while True: It will continue to
Line=input("Line:") take input till user
inputs a null entry

DPS RKP Computer Science Department


f.write(Line+"\n")
if len(Line)==0:
break Line:Those of us who love
Line:short stories know the
Line:magic behind a well-told
Line:tale.
Line:

18
Python Code for Text File with Functions
Write a Python Code with the following options to be executed using user
defined functions for each of them:

● To create a Text File and allow user to add new lines in it

DPS RKP Computer Science Department


● To append new lines in an existing file
● To display the content of a text file.

19
Function to create a Text File with user’s input
def SaveText():
with open("NOTES.TXT","w") as f:
while True:

DPS RKP Computer Science Department


L=input("Line:")
f.write(L+"\n")
M=input("More(Y/N)")
if M in ['N','n']:
break

20
Function to add content in Text File with user’s input
def AddText():
with open("NOTES.TXT","a") as f:
while True:
L=input("Line:")

DPS RKP Computer Science Department


f.write(L+"\n")
M=input("More(Y/N)")
if M in ['N','n']:
break

21
Function to read content of file & display on screen

def ReadText():
try:
with open("NOTES.TXT","r") as f:

DPS RKP Computer Science Department


L=f.readlines()
for i in L:
print(i,end="") Hello World
We are the World
except:
Thank you
print("File not found")

22
Function to read content of file & display on screen

def ReadText1():
try:
with open("NOTES.TXT","r") as f:

DPS RKP Computer Science Department


L=f.readlines()
for i in L:
Hello World
print(i)
except: We are the World
print("File not found")
Thank you

23
Creation of File with user’s input
while True:
C=input("S:Save R:Read 1:Read1 A:AddText Q:Quit>>>")
if C=='S':
S:Save R:Read 1:Read1 A:AddText Q:Quit>>>S
SaveText() Line:Hello World

DPS RKP Computer Science Department


elif C=='R': More(Y/N)Y
ReadText() Line:We are the World
elif C=='1': More(Y/N)N
ReadText1() S:Save R:Read 1:Read1 A:AddText Q:Quit>>>A
elif C=='A': Line:Thank you
AddText() More(Y/N)N
else: S:Save R:Read 1:Read1 A:AddText Q:Quit>>>R
Hello World
break
We are the World
Thank you
S:Save R:Read 1:Read1 A:AddText Q:Quit>>>S 24
Function to Read Text File & Display each word separated by *

def WordStr(): A:AddText W:WordStar Q:QuitA


try: Line:Hello
f=open("RANDOM.TXT","r") More(Y/N)Y
L=f.readlines() Line:How are you?

DPS RKP Computer Science Department


for i in L: More(Y/N)N
for w in i.split():
A:AddText W:WordStar Q:QuitW
print(w,end="*")
f.close() Hello*How*are*you?*
except: A:AddText W:WordStar Q:QuitQ
print("File not found")
Hello
for w in i.split(): How
print(w) are
you?
25
Function to Read Text File & Display each word separated by *

def WordStr(): A:AddText W:WordStar Q:QuitA


try: Line:Hello
f=open("RANDOM.TXT","r") More(Y/N)Y
L=f.readlines() Line:How are you?

DPS RKP Computer Science Department


for i in L: More(Y/N)N
for w in i.split():
A:AddText W:WordStar Q:QuitW
print(w,end="*")
f.close() Hello*How*are*you?*
except: A:AddText W:WordStar Q:QuitQ
print("File not found")
Hello
for w in i.split(): How
print(w) are
you?
26
Function to find number of Vowels found in Text File
def VowelCount(): RANDOM.TXT
try: HELLO
with open("RANDOM.TXT","r") as f:
WORLD OF
V=0
PEACE

DPS RKP Computer Science Department


while True:
C=f.read(1)
if C !="":
if C in "aeiouAEIOU":
V+=1
else:
break
print("Vowels",V)
except FileNotFoundError:
print("File Not Found") Vowels 7
27
Function to find number of Vowels found in Text File
RANDOM.TXT
def VowelCount(): #Option 2
try: HELLO
with open("RANDOM.TXT","r") as f: WORLD OF
V=0 PEACE

DPS RKP Computer Science Department


CA=f.read()
for C in CA:
if C in "aeiouAEIOU":
V+=1
print("Vowels",V)
except FileNotFoundError:
print("File Not Found")

Vowels 7
28
Function to display each line of Text file in reversed
def RevDisplay(): RANDOM.TXT
try: HELLO
with open("RANDOM.TXT","r") as f: WORLD OF
PEACE

DPS RKP Computer Science Department


L=f.readlines()
for i in L:
print(i[::-1],end="")
OLLEH
except FileNotFoundError: FO DLROW
print("File Not Found") ECAEP

29
Display Number of alphabets, digits, spaces in text file
try: # OPTION 1 RANDOM.TXT
with open("RANDOM.TXT","r") as f:
1 Sun
L=f.readlines()
a,d,s=0,0,0 9 planets
for i in L: all around us

DPS RKP Computer Science Department


for c in i:
if c.isalpha(): # c.lower() in "abcdefghijklmnopqrstuvwxyz"
a+=1
elif c.isdigit(): # c in "0123456789":
d+=1
elif c==" ": Al: 21 Dg: 2 Sp: 5
s+=1
print("Al:",a,"Dg:",d,"Sp:",s)
except FileNotFoundError:
print("File Not Found")
30
Display Number of alphabets, digits, spaces in text file
RANDOM.TXT
try: # OPTION 2
with open("RANDOM.TXT","r") as f: 1 Sun
L=f.read() 9 planets
a,d,s=0,0,0 all around us

DPS RKP Computer Science Department


for c in L:
if c.isalpha(): # c.lower() in "abcdefghijklmnopqrstuvwxyz"
a+=1
elif c.isdigit(): # c in "0123456789":
d+=1
elif c==" ":
Al: 21 Dg: 2 Sp: 5
s+=1
print("Al:",a,"Dg:",d,"Sp:",s)
except FileNotFoundError:
print("File Not Found")
31
Function to display line ending with ‘y’ or ‘Y’
def EndingwithY(): RANDOM.TXT
try: Wishing
with open("RANDOM.TXT","r") as f: you a peaceful
day

DPS RKP Computer Science Department


L=f.readlines()
smiling day
for i in L:
l=len(i)
if i[l-2] in ['y','Y']: # if i[-2] in ['y','Y']:
print(i,end="")
except FileNotFoundError: day
print("File Not Found") smiling day

32
Additional Functions - To do
1. Display alternate lines of a file (at index 0,2,4...) using
L=f.readlines()
for i in range(0,len(L),2):

DPS RKP Computer Science Department


print(L[i])
2. Displaying the content of a file in reverse (i.e. last line first) using
L=f.readlines()
for N in (L[::-1]):
print(N)
3. Display the content of Text file with each word in the reversed order.
4. Display the lines which start with “the” or “THE” or “The” from a Text file
5. Count the number of word “India” present in a Text File
6. Display the content without displaying spaces from a Text File
33
Positioning file pointer and knowing its position
<FileObject>.seek(<Offset>,[<From_What>])
Offset: Number of positions to move forward/backwards.
From_What (Optional): Defines the point of reference.

DPS RKP Computer Science Department


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
Returns: Does not return any value

with open("AB.TXT") as F: 0123456789012345 AB.TXT


F.seek(11) We are the world
CH=F.read(5) We are the children
print(CH) world
34
Let us save the lines of Text in file “SaveText()”
def SaveText():
with open("DIARY.TXT","w") as F:
F.write("0123456789\n")

DPS RKP Computer Science Department


F.write("ABCDEFGHIJ\n")
F.write("0123456789\n")
F.write("abcdefghij\n")
F.write("0123456789\n")

35
Displaying Content Option 1 - Using seek()
def ShowText1():
try:
with open("DIARY.TXT") as F:
for i in range(5):

DPS RKP Computer Science Department


try:
F.seek(i)
S:SaveText 1:ShowText1
C=F.read(i+1)
2:ShowText2 3:ShowText3
print(C)
Q:Quit1
except: 0
break 12
except: 234
print("File Not Found!") 3456
45678

36
Displaying Content Option 2 - Using seek()
def ShowText2():
try:
with open("DIARY.TXT") as F:
for i in range(5):

DPS RKP Computer Science Department


try:
F.seek(i) S:SaveText 1:ShowText1
C=F.read(i+1) 2:ShowText2 3:ShowText3
print("*"*(5-i),C) Q:Quit2
except: ***** 0
break **** 12
except: *** 234
print("File Not Found!") ** 3456
* 45678

37
Displaying Content Option 3 - Using seek()
def ShowText3():
try:
with open("DIARY.TXT") as F:
for i in range(5): S:SaveText 1:ShowText1

DPS RKP Computer Science Department


try: 2:ShowText2 3:ShowText3
F.seek(10*i+i) Q:Quit3
C=F.read(i+1)
print("*"*(5-i),C,"#",F.tell())
except:
***** 0 # 1
break
**** AB # 13
except:
*** 012 # 25
print("File Not Found!")
** abcd # 37
* 01234 # 49

38
Displaying Content Option 3 - Using seek()
while True:
CH=input("S:SaveText 1:ShowText1 2:ShowText2 3:ShowText3 Q:Quit")
if CH in "sS":
SaveText()

DPS RKP Computer Science Department


elif CH in "1":
ShowText1()
elif CH in "2":
ShowText2()
elif CH in "3":
ShowText3()
elif CH in "qQ":
break
else:
print("Invalid Option")
39
Let us save the Text in a file “Create()” as binary code
def Create():
with open('test.txt','wb') as F:
F.write(b"We are the world\n")
F.write(b"We are the children\n")

DPS RKP Computer Science Department


F.write(b"We are the ones who make a brighter day,\n")
F.write(b"so let's start giving\n")
F.write(b"There's a choice we're making\n")
F.write(b"We're saving our own lives\n")

pre-fixing b in front of the TEXT/STRING, the TEXT


will be saved as binary code on the storage device

40
Displaying Content - Using seek(<offset>,<From_Whence>)
Opening the file with rb mode is must to use From_Whence
def Display():
with open('test.txt','rb') as F:
# move 21 characters back from end character of file
F.seek(-21,2)

DPS RKP Computer Science Department


# starts reading from the point of file pointer
print(F.read(6).decode('utf8'))
# move five characters ahead from current location
F.seek(5,1)
print(F.read(3).decode('utf8'))
# move to the 11 character ahead from the start saving
F.seek(11, 0) # Same as without second parameter own
print(F.read(5).decode('utf8')) world

Suggested to use try...except


wherever required to avoid unhandled exception 41
Displaying Content - Using seek(<offset>,<From_Whence>)
Opening the file with rb mode is must to use From_Whence
def Display2():
with open('test.txt','rb') as F:
# move 21 characters back from end character of file
F.seek(-21,2)

DPS RKP Computer Science Department


# starts reading from the point of file pointer
print(F.read(6)) # Reading & displaying without decode
# move five characters ahead from current location
F.seek(5,1) # Reading & displaying without decode
print(F.read(3))
# move to the 11 character ahead from the start b'saving'
F.seek(11, 0) # Same as without second parameter b'own'
print(F.read(5)) # Reading & displaying b'world'
# without decode
Suggested to use try...except
wherever required to avoid unhandled exception 42
Displaying Content - Using seek(<offset>,<From_Whence>)
Create()
Display()

DPS RKP Computer Science Department


We are the world\n
We are the children\n
We are the ones who make a brighter day,\n
so let's start giving\n
There's a choice we're making\n
We're saving our own lives\n
109876543210987654321
saving
F.seek(-21,2)
print(F.read(6).decode('utf8'))
43
Displaying Content - Using seek(<offset>,<From_Whence>)
Create()
Display()

DPS RKP Computer Science Department


We are the world\n
We are the children\n
We are the ones who make a brighter day,\n
so let's start giving\n
There's a choice we're making\n
We're saving our own lives\n
12345
own
F.seek(5,1)
print(F.read(3).decode('utf8')) 44
Displaying Content - Using seek(<offset>,<From_Whence>)
Create()
Display() world
012345678901

DPS RKP Computer Science Department


We are the world\n
We are the children\n
We are the ones who make a brighter day,\n
so let's start giving\n
There's a choice we're making\n
We're saving our own lives\n

F.seek(11, 0)
print(F.read(5).decode('utf8')) 45
Text File - write() and writelines()
write() - A function to write a single value of a string into the file stream

writelines() - A function to write a tuple/list of a string into the file stream


["First Line!\n","More Lines.\n","Ends here\n"]

DPS RKP Computer Science Department


def Create():
with open("test.txt", "w") as F:
F.writelines(("First Line!\n","More Lines.\n","Ends here\n"))
def Disp():
with open("test.txt", "r") as F:
for i in F.readlines():
print(i,end="")
Create()
Disp()

46
Text File - readlines() and readlines(n)
readlines() - A method to read entire content as list of strings

readlines(n) - A method to read at most n bytes from the file and stops at the
next line boundary (i.e.till the next newline character)
["First Line!\n","More Lines.\n","Ends here\n"]

DPS RKP Computer Science Department


def First():
f = open("test.txt", "w")
N=int(input("N:"))
L=f.readlines(n)
# N -> 1-11 will extract
# ["First Line!\n"]
# N -> 12-22 will extract
# ["First Line!\n","More Lines.\n"
# N -> 23 and above will extract
# ["First Line!\n","More Lines.\n","Ends here\n"]
print(L);F.close() 47
Recap
read() readline() readlines()

Reads the entire content from Reads a single line from the text Reads the entire content from
the text file as a string file as a string the text file as a list of strings

DPS RKP Computer Science Department


read(n) readline(n) readlines(n)

Reads n characters from current Reads n characters from current If n is specified, the method
position of the file pointer position of the file pointer reads at most n bytes from the
However, will terminate the file and stops at the nearest line
content if new line character is boundary.
encountered.
writelines()
write()
Writes content from a tuple/list
Writes content from a single of strings
string
48
Mounting Google Drive in colab
from google.colab import drive
drive.mount('/content/drive', force_remount=True)

DPS RKP Computer Science Department


def Create():
with open("/content/drive/My Drive/diary.txt","w") as F:
F.write("Hello\n")
F.close()

def Disp():
with open("/content/drive/My Drive/diary.txt") as F:
ALL=F.read()
print(ALL)
49
Mounting Google Drive in colab
For saving and retrieving content from Data File in colab, it is essential to mount
the Google Drive every time, you start colab with the help of following code:
from google.colab import drive
drive.mount('/content/drive', force_remount=True)

DPS RKP Computer Science Department


After mounting, use the following file path for accessing data file:
def Create():
with open("/content/drive/My Drive/diary.txt","w") as F:
F.write("Hello\n")
F.close()
def Disp():
with open("/content/drive/My Drive/diary.txt") as F:
ALL=F.read()
print(ALL)
50
Happy Learning…

DPS RKP Computer Science Department


Thank you!
Department of Computer Science

51

You might also like