08 - Python Data Files 1 XII - CS - 2025-2026
08 - Python Data Files 1 XII - CS - 2025-2026
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
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
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
STORY.PY STORY.TXT
# Python Code to Those of us who love
5
Flow of Control - Code to Read from Text File
STORY.TXT STORY.PY
Those of us who love # Python Code to
6
Opening and closing text files [Alternate 1]
Opening a text file
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("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
9
Flow of Writing/Appending the Text in the File
F.write(TXT+"\n")
F SAMPLE.TXT
Hello Friends
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!
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.
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:
13
Use of readline() method to read content from file
readline() reads the next line of characters from the standard input stream.
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()
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)
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:
19
Function to create a Text File with user’s input
def SaveText():
with open("NOTES.TXT","w") as f:
while True:
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:")
21
Function to read content of file & display on screen
def ReadText():
try:
with open("NOTES.TXT","r") as f:
22
Function to read content of file & display on screen
def ReadText1():
try:
with open("NOTES.TXT","r") as f:
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
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
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
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):
35
Displaying Content Option 1 - Using seek()
def ShowText1():
try:
with open("DIARY.TXT") as F:
for i in range(5):
36
Displaying Content Option 2 - Using seek()
def ShowText2():
try:
with open("DIARY.TXT") as F:
for i in range(5):
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
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()
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)
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
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"]
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
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)
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)
51