● 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 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
● Binary file: basic operations on a binary file: open using file open modes (rb, rb+, wb,
wb+, ab, ab+), close a binary file, import pickle module, dump() and load() method,
read, write/create, search, append and update operations in a binary file
● CSV file: import csv module, open / close csv file, write into a csv file using
writer(),writerow(),writerows() and read from a csv file using reader()
● Data Structure: Stack, operations on stack (push & pop), implementation of stack
using list
Q.1 What is a file?
Ans
A file is a stream or sequence of characters/ bytes occupying a specific location on the
disk or any permanent storage medium..
Computers store every file as a collection of 0s and 1s i.e., in binary form.
Therefore, every file is basically just a series of bytes stored one after the other.
There are mainly two types of data files — text file and binary f ile.
A text file consists of human readable characters, which can be opened by any text
editor.
On the other hand, binary files are made up of non-human readable characters and
symbols, which require specific programs to access its contents
Q.2 What are the different types of files?
Ans
1. Text When some encoding scheme is applied to the contents of the file
and then stored on the disk.
In a text file each line is terminated by the special character known as (End
of Line) EOL character.
By default this EOL character is ‘\n’.
A text file can be created and opened using any text editor and the output is
in human readable form.
2. Binary
Are used to store binary data such as images, video, audio etc.
It contains arbitrary data stored as bytes.
We need to convert the data to it’s appropriate form using equivalent
programs.
Since these are not text files there is no delimiter for a line.
Also there are no character translations.
Binary files are easier and faster for reading and writing data
Q. 18 What is the difference between absolute and relative path with
respect to the location of files on the disk?
Ans
Files are always stored in the current directory by default.
A relative path starts from the current directory, whereas the absolute path
starts from the topmost directory or root directory.
The absolute path (also known as the full path) of an entity contains the
complete information (from the root to the ending) needed to locate it.
The absolute path is not affected by the user’s current working directory,
and it always includes the root directory as a starting point.
The relative path of an entity contains the information needed to locate that
entity relative to the user’s current working directory.
The relative path disregards the information needed to locate the current
working directory from the root directory and only focuses on the route
from the working directory to the entity.
What will be the relative path to locate cheesecake.doc from location G
..\Home\F\Documents\Recipes\cheezecake.doc
What will be the relative path to locate cheesecake.doc from location U
..Expenses\..D\ Home\F\Documents\Recipes\cheezecake.doc
The absolute path to locate Funny.py is :
D:\Occassions\N\Birthdays\Funny.py
The absolute path to locate cheesecake.doc is :
D:\Home\F\Documents\Recipes\Cheezecake.doc
The relative path to locate Funny.py if the working directory is Birthdays is:
Funny.doc since the file is in the working directly itself.
The relative path of a file cheesecake.doc if the working directory is
Reminders is ..\Recipes\cheezecake.doc.
The .. is used to go up one level
The relative path of a file cheesecake.doc if the working directory is
Documents is \Recipes\cheezecake.doc.
The relative path of a file cheesecake.doc if the working directory is
Documents is \Recipes\cheezecake.doc.
Q.3 What are the different modes in which a file can be opened?
Ans
The first thing that must be done before a file can be read or saved is to
open it. The open() function takes the name of the file as the first argument.
The second argument indicates the mode. The file mode indicates how the
file will be accessed.
The different modes in which files can be opened are:
1. read (r)
2. write (w)
3. append (a)
f=open(‘notes.txt’, ‘r’) The type of file opened is text file and the mode is
read.
f=open(‘notes.txt’) The type of file opened is text file and the mode is read.
F=open(‘notes’, ‘wb’) type of file is binary and mode is write
f=open(‘notes’, ‘w’) type of file is text and mode is write
The syntax for the open() function is as follows:
File variable/File object =open(file_name, mode)
Example: F=open(“Test.txt”,’w’)
This will open the file with name “Test.txt” in ‘write’ mode.
It will be referred to in the program as F.
Q.4 List out the different file modes?
Ans
Q.5 Write command to close file object F?
Ans
F.close()
fileobject. close() will be used to close the file object, once we have
finished working on it.
The method will free up all the system resources used by the file, this
means that once file is closed, we will not be able to use the file object any
more.
Before closing the file any material which is not written in file, will be
flushed off.
So it is good practice to close the file once we have finished using it.
In case, if we reassign the file object to some other file, then python will
automatically close the file
Q.6 List out properties of the file object?
Ans 1.
Name
returns the name of the file object
Example:
f=open("test.txt",'w')
print("File name =", f.name)
>>>File name= test.txt
2. mode returns the mode in which the file was opened
Example:
f=open("test.txt",'w')
print("Mode =", f.mode)
>>> Mode = w
3. closed
returns Boolean value, which indicates whether the file is closed Or not
Example:
f=open("test.txt",'w')
print("Is file closed? ", f.closed) f.close()
print("Is file closed? ", f.closed)
>>>
Is file closed? False
Is file closed? True
4. readable()
returns Boolean value, which indicates whether the file is readable or not
Example:
f=open("test.txt",'w')
print("Is the file readable?", f.readable())
>>> Is the file readable? False
Text Files (.txt)
readline() First call to file object keeps x = file.readline()
function will return the track of from or
first line including where reading / print file.readline()
the end of line writing of data
character, second should happen for line in file: …
call next line and print line
so on in string When end of file is
format reached, readline()
will return an
empty string
readlines() can be used to The method will fileobject.readlines()
read the entire return a list of
content of the file strings, each list can be used to
separated by \n. manipulate
You need to be
careful while using
it w.r.t. size of
memory required
before using the
function
read() can be used to At the end of the fileobject.read([size])
read specific size file, again an
string from file. empty string will size specifies the
returns a string be returned. number of bytes to
read from the file. be read from the file
take care of
If the value of size memory size
is not provided or available before
a negative value is reading the entire
specified as size content from the
then entire file will file.
be read.
Q.7 List out the methods for reading from a file?
Ans
read()
To read the entire file, starting from the cursor till the end of the file.
Returns a string.
Example:
Contents of notes.txt:
Hello Students,
Now start coding…
Code fragment:
f=open("notes.txt", 'r')
data=f.read()
print(data) f.close()
>>> Hello Students,
Now start coding…
2. read(n)
To read n characters, starting from the cursor till the end of the file.
If there are fewer than n characters, it will read till end of file.
Returns a string.
f=open("notes.txt", 'r')
data=f.read(10)
print(data)
f.close()
>>> Hello Stud
3
readline()
To read only one line, starting from the cursor till the end of the line
including the end of line character.
Returns a string.
f=open("notes.txt", 'r')
line =f.readline()
print(line)
f.close()
>>>
Hello Students,
To read all the lines, starting from the cursor till the end of the line
including the end of line character. Returns a string containing a line
including an EOL character ‘\n’.
f=open("notes.txt", 'r')
line =f.readline()
print(line)
f.close()
>>>
Hello Students,
4. readlines()
To read all lines, starting from the cursor till the end of the file and
returns a list of lines. Since the each line ends with a ‘\n’ there are
blank lines between each line in the output.
To remove the extra blank lines we can use the strip() function.
Example:
f=open("notes.txt", 'r')
lines =f.readlines()
for line in lines:
line=line.strip()
print(line)
f.close()
>>>
Hello Students,
Now start coding...
How the list looks ['Hello, World!\n', 'Python is fun.\n', "Let's
learn file handling."]
Q.8 List out the methods for writing to a file?
Ans
1. write(string)
write() method takes a string ( as parameter ) and writes it in
the file
For storing data with end of line character, you will have to add
\n character to end of the string
As argument to the function has to be string, for storing
numeric value, we have to convert it to string.
Writes a string to the data file.
f=open("somestuff.txt", 'w')
n=input(“Enter any text”)
f.write(n)
f.close()
f=open("somestuff.txt")
line=f.readline()
while line:
print(line)
line=f.readline()
f.close()
Example
f = open('test1.txt','w')
f.write("hello world\n")
f.close()
For numeric data value conversion to string is required.
Example
x = 52
file.write(str(x))
For writing a string at a time, we use write() method, it can't be used
for writing a list, tuple etc. into a file.
Sequence data type can be written using writelines() method in the file.
we can't write a string using writelines() method also
2. writelines(seq)
Write a sequence of lines to a file.
The write operation could be from a list or any sequential data
structure. Or it could be multiple strings, but the new line
character is not added to the file, it has to be explicitly added to
the lines which are to be written to the file.
f=open("somestuff.txt", 'w')
times=2
list1=[]
for t in range(times):
x=input("Enter some world event")
x=x+"\n"
list1.append(x)
f.writelines(list1)
f.close()
f=open("somestuff.txt", 'r')
line=f.readline()
while line:
print(line)
line=f.readline()
f.close()
f = open('test2.txt','w')
str = 'hello world.\n this is my first file handling program.\n I am
using python language"
f.writelines(str)
f.close()
let's consider an example of creation and reading of file in
interactive mode
file = open('test.txt','w')
s = ['this is 1stline','this is 2nd line']
file.writelines(s)
file.close()
file.open('test.txt') # default access mode is r
print file.readline()
file.close()
Will display following on screen
this is 1stline this is 2nd line
# s = ['this is 1st line\n', 'this is 2nd line\n']
3. with
This statement takes care of automatically closing the file object
after all the file operations enclosed within the with statement are
executed.
Example:
with open("examples.txt", 'w') as f:
f.write("Hello \n")
f.write("With the with statement we can perform \n")
f.write("multiple operations with same file object \n")
f.write("After the operations the file object is closed
automatically")
print("Is the file object closed?", f.closed)
print("Is the file object closed?", f.closed)
>>> Is the file object closed? False
Is the file object closed? True
To access the contents of file randomly - seek and tell
methods are used.
tell() method returns an integer giving the current position
of object in the file.
The integer returned specifies the number of bytes from the
beginning of the file till the current position of file object.
It's syntax is fileobject.tell()
Q.14
Which function can change the position of the file pointer in a
file? What is the syntax?
Ans
seek()
In Python, seek() function is used to change the position of the
File pointer to a given specific position. File pointer is like a
cursor, which defines the position where the data is to be read
or written in the file.
Syntax for the seek function:
Syntax: f.seek(offset, from_what), where f is file pointer
Parameters:
Offset: Number of positions to move forward from_what:
It defines point of reference.
Returns: Does not return any value
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.
Eg. The file story.txt contains the following text:
Whose woods these are I think i know
His house is in the village though,
He will not see me stopping by
To watch his woods fill up with snow
To open the file and set the file pointer at the 6 position:
>>>f=open(“story.txt”)
>>>f.seek(6)
>>>contents=f.read(6)
>>>print(contents)
'woods '
It shows that the file pointer is first placed at position 6. Then 6
characters are read.
#example=============================
def fileHandling():
file = open("story.txt","w+")
while True:
line = raw_input("enter sentence :")
file.write(line)
choice = raw_input("want to enter more data in file Y / N")
if choice.upper() == 'N' :
break
file.seek(0)
lines = file.readlines()
file.close()
for l in lines:
print l
Q.15 Does the from_where argument of the seek function work
with text files?
In which mode will this argument work?
Ans
The from_where argument in the seek function does not work
when file is opened as a text file. It works only with binary files,
or when a file is opened in binary mode.
The following code demonstrates the file ‘story.txt’ is opened in
binary mode.
Then it is read from the end of the file since the from_where
argument is 2. It goes back 10 bytes from the end.
So the file pointer is at 137.
>>>f=open('story.txt','rb')
>>> f.seek(-10, 2)
>>>k=f.tell()
>>>print(k)
137
To convert the data back to text format and print it, the
following code is used:
>>> print(f.readline().decode('utf-8'))
Q.16
Which function is used to return the current position of the file
pointer?
Ans
tell() is the function used to return the current position of the
file pointer.
>>>f=open('story.txt’)
>>> k=f.tell()
>>>print(k) 0
>>>f.seek(10)
>>>k=f.tell()
>>>print(k)
10
when we want to work on binary file, conversion of data at
the time of reading, as well as writing is required.
Pickle module can be used to store any kind of object in file
as it allows us to store python objects with their structure.
So for storing data in binary format, we will use pickle
module.
use pickle.dump() to write the object in file, which is opened
in binary access mode.
Syntax of dump() method is: dump(object, fileobject)
Suntax of load() object = load(fileobject)
Q.10 What are the modules and functions provided by Python
to write binary data to files, like data from a dictionary, tuple
etc?
Ans
Python provides a module pickle which needs to be imported
for binary file operations.
This module provides the functions dump() and load() to save
or load binary data from and to a file.
Example:
import pickle
print("Saving to binary file:")
dict1={1:"A", 2:"B"} # list & dict both can be used
f=open("B.dat", 'wb') # b in access mode is for binary file
pickle.dump(dict1,f) # writing content to binary file
f.close()
print("Loading binary file data:")
f=open("B.dat", 'rb')
d1=pickle.load(f)
f.close()
print(d1)
‘’’
Example of storing multiple integer values in a binary file
and then read and display it on screen:
def binfile():
import pickle # line 1
file = open('data.dat','wb') # line 2
while True:
x = int(raw_input()) # line 3
pickle.dump(x,file) # line 4
ans = raw_input('want to enter more data Y / N')
if ans.upper()== 'N' :
break
file.close() # line 5
file = open('data.dat','rb') # line 6
try : # line 7
while True : # line 8
y = pickle.load(file) # line 9
print y # line 10
except EOFError : # line 11
pass
file.close() # line 12
‘’’
Q.11 Write code to append 5 names in list L1 and save the list
to the disk as a binary file L1.dat.
Ans
import pickle
L1=[]
x=0
while x:
r=input(“Enter name:”)
L1.append(r)
x+=1
f=open(“L1.dat”, “wb”)
pickle.dump(L1, f)
f.close()
Q.12 Write the code to load a binary file L1.dat from the disk
into a list L1.
Ans
import pickle
L1=[]
f=open(“L1.dat”, “rb”)
L1=pickle.load(f)
f.close()
for i in range(len(L1)):
print(Li[i])
Q.12 Write the code to save a dictionary with first 5 numbers
with their matching Roman numerals to the disk as a binary file
D1.dat.
Ans
import pickle
f=open(“D1.dat”, “wb”)
D1={1:’I’,2:’II’, 3:’III’, 4:’IV’, 5:’V’ }
pickle.dump(D1, f)
Q.13 Write the code to load the binary file D1.dat from the disk
into a dictionary object D1.
Ans
import pickle
D1={}
f=open(“D1.dat”, “rb”)
D1=pickle.load(f)
print(D1)
Files are used to store huge collection of data permanently.
The stored data can later be used by performing various file
operations like opening, reading, writing etc.
Access modes specify the type of operations to be
performed with the opened file.
read(), readline() and readlines() methods are available for
reading data from the file.
write() and writelines() are used for writing data in the file.
There are two functions which allow us to access a file in a
non-sequential or random mode.
They are seek() and tell()
Serialization is the process of converting a data structure /
object that can be stored in non string format and can be
resurrected later.
Serialization can also be called as deflating the data and
resurrecting as inflating it.
Pickle module is used in serialization of data. This allow us
to store data in binary form in the file.
Dump and load functions are used to write data and read
data from file.
os module provide us various functions and attributes to
work on files.
Q. 16 What are file streams?
Ans Files streams are file objects that get connected to the
program’s standard devices when Python is started. In order to
work with I/O streams, the module that must be imported is
‘sys’.
Q. 17 Which are the standard file streams in Python?
Ans The standard file streams in Python are as follows: i.
sys.stdin – when the stream reads bytes from standard input
device(keyboard) ii. sys.stdout – when the data is transferred to
the standard output device(monitor) iii. sys.stderr – when the
errors are stored in a file stderr
Q.9 What is pickling and unpickling? Ans Pickling refers to the
process of converting a data structure to a byte stream before it
can be written to a binary file. In other words it is also said to be
used in object serialization. Unpickling refers to the process of
converting the byte stream from the binary file back to the
original structure. In other words it is also to be used in object
de-serialization. Object Items: ItemcodeDescriptionPriceQty
122Pen2510123Pencil10100
CSV files are a middle ground between text files and binary
files, offering readability and structure while remaining
lightweight.
Let's compare CSV with text and binary files for data
storage.
CSV vs. Text Files
Why CSV over Text?
• CSV organizes data into structured rows & columns.
• Easier to process programmatically (e.g., in Python).
• CSV handles large datasets better than unstructured text files.
#CSV vs. Binary Files
Why CSV over Binary?
• CSV is easier to share, edit, and process across platforms.
• No need for specialized tools (text editors can open it).
• More portable compared to binary files, which may have format
incompatibilities.
• Why Use CSV for Permanent Storage?
• ✔ More structured than text files → Easier to process.
✔ More readable than binary files → Portable and human-friendly.
✔ Supported by most programming languages, databases, and spreadsheet
software (Excel, MySQL, etc.).
✔ Universally compatible across different operating systems without format
issues.
A CSV file is stored in a format very close to a text file and it can be opened in any
simple text editor. A CSV file can be processed like a binary file using the functions
of CSV module like Reader and Writer to read and write objects to the file.
a. Give any one point of difference between a binary file and a csv file.
Ans:
A csv file is stored as human readable characters and can be read in any simple text
editor. A binary file is stored as a stream of bytes and cannot be opened and read in
simple text editors.
1. Importing the csv Module
Before working with CSV files, you must import the csv module:
import csv
2. Writing to a CSV File (writer(), writerow(), writerows())
The writer() method creates a CSV writer object, which can
write rows of data to a CSV file.
Writing a Single Row using writerow()
import csv
# Open file in write mode
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file) # Create writer object
writer.writerow(["Name", "Age", "Grade"]) # Writing a header
writer.writerow(["Alice", 14, "A"]) # Writing one row
writer.writerow(["Bob", 15, "B"]) # Writing another row
print("CSV file created successfully.")
‘’’
Name,Age,Grade
Alice,14,A
Bob,15,B
‘’’
Writing Multiple Rows using writerows()
import csv
# Data to write
students = [
["Name", "Age", "Grade"], # Header
["Charlie", 16, "A"],
["David", 15, "B"],
["Eve", 14, "A"]
]
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(students) # Writing multiple rows at once
print("CSV file created successfully.")
3. Reading from a CSV File (reader())
The reader() method reads a CSV file line by line.
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file) # Create reader object
for row in reader:
print(row) # Each row is a list
‘’’
['Name', 'Age', 'Grade']
['Charlie', '16', 'A']
['David', '15', 'B']
['Eve', '14', 'A']
‘’’
2⃣ What is newline="" in open()?
When working with CSV files, we often use newline="" in
open().
Why?
• Prevents extra blank lines in Windows when writing CSV files.
• Ensures correct line breaks across different operating systems.
• Helps maintain proper CSV formatting.
csv.reader() and csv.writer() ensure structured row-wise
operations.
3⃣ Using f.read() or f.write() for CSV files leads to formatting
issues.
It thus follows the Last-In-First-out (LIFO) principle. That is, the element
which was inserted last (the most recent element) will be the first one
to be taken out from the stack.
PUSH adds a new element at the TOP of the stack. It is an insertion
operation. We can add elements to a stack until it is full. A stack is full
when no more elements can be added to it. Trying to add an element to a
full stack results in an exception called ‘overflow’.
POP operation is used to remove the top most element of the stack, that is,
the element at the TOP of the stack. It is a delete operation. We can delete
elements from a stack until it is empty i.e. there is no element in it. Trying to
delete an element from an empty stack results in an exception called
‘underflow’
A stack is used insert and delete elements in LIFO order.
a stack is a linear and ordered collection of elements. The simple way to
implement a stack in Python is using the data type list
#assigning an empty list
glassStack = list()
#A function named isEmpty to check whether the stack glassStack is
empty or not
def isEmpty(glassStack):
if len(glassStack)==0:
return True
else:
return False
#A function named opPush to insert (PUSH) a new element in stack.
def opPush(glassStack,element):
glassStack.append(element)
#A function named size to read the number of elements in the glassStack
def size(glassStack):
return len(glassStack)
#A function named top to read the most recent element (TOP) in the
glassStack.
def top(glassStack):
if isEmpty(glassStack):
print('Stack is empty')
return None
else:
x =len(glassStack)
element=glassStack[x-1]
return element
#A function named opPop to delete the topmost element from the stack. It
takes one parameter - the name of the stack (glassStack) from which
element is to be deleted and returns the value of the deleted element.
def opPop(glassStack):
if isEmpty(glassStack):
print('underflow')
return None
else:
return(glassStack.pop())
#A function named display to show the contents of the stack.
def display(glassStack):
x=len(glassStack)
print("Current elements in the stack are: ")
for i in range(x-1,-1,-1):
print(glassStack[i])
Once we define the above functions we can use the following Python code
to implement a stack of glasses.
glassStack = list() # create empty stack #add elements to stack
element='glass1'
print("Pushing element ",element)
opPush(glassStack,element)
element='glass2'
print("Pushing element ",element)
opPush(glassStack,element)
#display number of elements in stack
print("Current number of elements in stack is",size(glassStack))
#delete an element from the stack
element=opPop(glassStack)
print("Popped element is",element)
#add new element to stack
element='glass3'
print("Pushing element ",element)
opPush(glassStack,element)
#display the last element added to the #stack
print("top element is",top(glassStack))
#display all elements in the stack
display(glassStack)
#delete all elements from stack
while True:
item=opPop(glassStack)
if item == None:
print("Stack is empty now")
break
else:
print("Popped element is",item)
The output of the above program will be as follows:
Pushing element glass1
Pushing element glass2
Current number of elements in stack is 2
Popped element is glass2
Pushing element glass3
top element is glass3
Current elements in the stack are: glass3 glass1
Popped element is glass3
Popped element is glass1
Underflow Stack is empty now