You are on page 1of 17

File Handling in Python

A. Introduction
All programs need the input to process and output to display data. And everything
needs a file as name storage compartments on computers that are managed by OS.
Though variables provide us a way to store data while the program runs, if we want
out data to persist even after the termination of the program, we have to save it to a
file.

B. Types of Files

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 file. 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.

C. 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. When we open a text file using a text editor (e.g.,
Notepad), we see several lines of text.

Operation on Text File


1.Open() 2.Writing() 3. Close() 4. Appending 5. Reading() 6. Seek()
and Tell() Function, Absolute vs. Relative Paths 7. Standard Input
/Output and Error Streams
1. Opening File
To open a file, you need to use the built-in open function. The open
function returns a file object that contains methods and attributes to
perform various operations on the file.
Syntax:
file_object = open("filename", ‘mode’)
filename: gives name of the file that the file object has opened.
mode: attribute of a file object tells you which mode a file was opened in.
Example:
f = open("demofile.txt", ‘w’)
There are 6 access modes in python text file.
Read Only (‘r’) : Open text file for reading. The handle is positioned at the
beginning of the file. If the file does not exists, raises I/O error. This is also
the default mode in which file is opened.
Read and Write (‘r+’) : Open the file for reading and writing. The handle is
positioned at the beginning of the file. Raises I/O error if the file does not
exists.
Write Only (‘w’) : Open the file for writing. For existing file, the data is
truncated and over-written. The handle is positioned at the beginning of the
file. Creates the file if the file does not exists.
Write and Read (‘w+’) : Open the file for reading and writing. For existing
file, data is truncated and over-written. The handle is positioned at the
beginning of the file.
Append Only (‘a’) : Open the file for writing. The file is created if it does not
exist. The handle is positioned at the end of the file. The data being written
will be inserted at the end, after the existing data.
Append and Read (‘a+’) : Open the file for reading and writing. The file is
created if it does not exist. The handle is positioned at the end of the file.
The data being written will be inserted at the end, after the existing data.
Example:
file = open('school.txt','w')
file.write("V Set Technology\n")
file.write("Academy of Computer Science")
file.close()
2. Writing onto files
To write strings into text data file you can use write() or writelines()
function. For writing you can open a file in ‘w’ or ‘w+’ or ‘r+’ mode.
Example:
file.write("Academy of Computer Science")
3. Closing Files
An open file is closed by calling the close() function of its object. Closing of
files is important in python, files are automatically closed at the end of the
program but it is good practice to get into the habit of closing your files
Example:
file.close()
4. Appending a file
You want to write into the file retaining the old data, then you should opent
the file “a” or append mode. A file opened in append mode retains its
previous data while allowing you to add newer data into.
Example:
file = open('c:\\school\\school.txt','w')
Q. Write a program to enter N no of student name ,class, roll no five
subject marks and calculate total , percentage and store these details in a
file called “STUDENT.TXT”.
Ans.
n=int(input("Enter no of student"))
f=open("student.txt","w")
for i in range(n):
print("Enter",(i+1)," student details",)
name=input("Enter name")
rollno=int(input("Enter roll no"))
cls=input("Enter Class")
m1=int(input("Enter ist subject marks"))
m2=int(input("Enter iist subject marks"))
m3=int(input("Enter iiist subject marks"))
m4=int(input("Enter vist subject marks"))
m5=int(input("Enter vst subject marks"))
tot=m1+m2+m3+m4+m5
per=tot/5

rec=name+","+str(rollno)+","+cls+","+str(m1)+","+str(m2)+","+str(m3)+","+s
tr(m4)+","+str(m5)+","+str(tot)+","+str(per)+"\n"
f.write(rec)
f.close()
output:
aaa,45,xii,50,40,60,70,80,300,60.0
bbbb,56,xi,10,20,30,40,50,150,30.0
Q. Write a program to add two more students detail to the file created
above
Answer:
f=open("student.txt","a")
for i in range(2):
print("Enter",(i+1)," student details",)
name=input("Enter name")
rollno=int(input("Enter roll no"))
cls=input("Enter Class")
m1=int(input("Enter ist subject marks"))
m2=int(input("Enter iist subject marks"))
m3=int(input("Enter iiist subject marks"))
m4=int(input("Enter vist subject marks"))
m5=int(input("Enter vst subject marks"))
tot=m1+m2+m3+m4+m5
per=tot/5

rec=name+","+str(rollno)+","+cls+","+str(m1)+","+str(m2)+","+str(m3)+","+s
tr(m4)+","+str(m5)+","+str(tot)+","+str(per)+"\n"
f.write(rec)
f.close()
Q Create a file to store five different name , separated lines
Answer:
f=open("studentname.txt","w")
f.write("Anuj\n")
f.write("Anil\n")
f.write("Ankur\n")
f.flush()
f.write("Ajay\n")
f.write("Amit\n")
f.close()
output:
Anuj
Anil
Ankur
Ajay
Amit
flush() :- The flush () function force the writing of data on disc still pending
in output buffer.
Q Create a file to store five different name , separated lines with the help of
writelines()
Answer:
f=open("studentname.txt","w")
list=[]
for i in range(5):
name=input("Enter name")
list.append(name+"\n")
f.writelines(list)
f.close()
Same output of above program
5. Reading from file
Mainly three types of read functions to read from a data file. 1. read() 2.
readline() 3. Readlines().
To read a file opened in reading mode either in “r”, ”r+”,”w+” or “a+”
opening mode
Example:
f=open("studentname.txt","r")
Q. Write a program to raed above studentname.txt file
Answer
f=open("studentname.txt","r")
str=f.read()
print(str)
f.close()
Same output of above program
Q. Write a program to raed above studentname.txt file only first 10
character
Answer
f=open("studentname.txt","r")
str=f.read(10)
print(str)
f.close()
Output:
anil
ankur
When we specify number of bytes with read(), Python will read only the
specified number of bytes from a file.
The readline() function read a full line. Aline is considered till a newline
character (EOL)”\n” is encountered in the data file.
Q. Write a program to read a file studentname.txt with the help of
readline() function
Answer
f=open("studentname.txt","r")
str=f.readline()
print(str)
str=f.readline()
print(str)
str=f.readline()
print(str)
str=f.readline()
print(str)
str=f.readline()
print(str)
f.close()
output:
anil

ankur
ajay

amit

anubhav
The readline() function reads the leading and trailing space(if any) along
with trailing newline character(‘\n’) also while reading the line. You can
remove these leading and trailing white spaces using strip() function
without any arguments.
Example:
f=open("studentname.txt","r")
str=f.readline()
print(str.strip())
str=f.readline()
print(str.strip())
str=f.readline()
print(str.strip())
str=f.readline()
print(str.strip())
str=f.readline()
print(str.strip())
f.close()
output:
anil
ankur
ajay
amit
anubhav
Q. Write a program to read a file studentname.txt with the help of
readlines() function
Answer
f=open("studentname.txt","r")
str=f.readlines()
print(str)
f.close()
output:
['anil\n', 'ankur\n', 'ajay\n', 'amit\n', 'anubhav\n']
Difference between readline() and readlines() function
The readline() function reads from a file in read mode and returns the next
line in the file or a blank string if there are no more lines. The returned data
is of string type.
The readlines() function also reads from a file in read mode and returns a
list of all lines in the file.
The returned data is of list type.
Q Write a program to display the size of a file in bytes
Answer
f=open("studentname.txt","r")
str=f.read()
size=len(str)
print("Size of given file is",size,"bytes")
output
Size of given file is 29 bytes

Q Write a program to display the number of lines in the file.


Answer
f=open("studentname.txt","r")
str=f.readlines()
linecount=len(str)
print("Number of lines of the given files ",linecount)
output
Number of lines of the given files 5
6.
A. Seek () and Tell() function
Tell() function
The tell() method returns the current file cursor (pointer) position in a file
stream.
Syntax:
file.tell()
Example:
f = open("demofile.txt", "r")
print(f.readline())
print(f.tell())
Seek () function
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.
Syntax: f.seek(offset, from_what)
Parameters:
Offset: Number of positions to move forward
from_what: It defines point of reference.
Returns: Return the new absolute position.
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.
Note: Reference point at current position / end of file cannot be set in text
mode except when offset is equal to 0.
f=open("student.txt", "r")
print(f.tell())
f.seek(3)
print(f.read(3))
f.seek(6)
print(f.read())
f.close()

To perform reading and writing operation in a text file


fileobject=open("report.txt", "w+")
print ("WRITING DATA IN THE FILE")
print() # to display a blank line
while True:
line= input("Enter a sentence ")
fileobject.write(line)
fileobject.write('\n')
choice=input("Do you wish to enter more data? (y/n): ")
if choice in ('n','N'): break
print("The byte position of file object is ",fileobject.tell())
fileobject.seek(0) #places file object at beginning of file
print()
print("READING DATA FROM THE FILE")
str=fileobject.read()
print(str)
fileobject.close()

B. Absolute vs. Relative Paths


There are two ways to specify a file path.
An absolute path, which always begins with the root folder
Example
file = open(r'c:\school\school.txt','w')
A relative path, which is relative to the program’s current working
directory
There are also the dot (.) and dot-dot (..) folders. These are not real folders
but special names that can be used in a path. A single period (“dot”) for a
folder name is shorthand for “this directory.” Two periods (“dot-dot”)
means “the parent folder.”
Example
file = open(r'..\school.txt','w')
Note:
The prefix r in front of a string makes it raw string that means there is no
special meaning attached to any character or you can use double slashes.
file = open('c:\\school\\school.txt','w')

6. Standard Input, Output and Error Streams


 Standard input device (stdin)-reads from Keyboard
 Standard output device(stdout)-prints to the display
 Standard error device(stderr)-Same as stdout but only for errors. If
error occurred python allows to separate output
These standard devices are implemented as file called standard streams.
In python, you can use these standard stream file by using sys module.
After importing you can use these standard streams (stdin, stdout and
stderr) in the same way as you use other files.
If you import sys module in your program then sys.stdin.read() would let
you read from keyboard. This is because the keybord is the standard
input device linked to sys.stdin. Similarly sys.stdout.write() would let you
you write on the standard output device, the monitor.
import sys
f=open("studentname.txt","r")
l1=f.readline()
l2=f.readline()
sys.stdout.write(l1)
sys.stdout.write(l2)
sys.stderr.write("No errors occurred\n")
f.close()

You might also like