File Handling in Python
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.
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