File Handling
Revision
                             TYPES OF FILES
    1. TEXT FILE
A file whose contents can be viewed using a text editor is called a text file. A text file is a
sequence of ASCII or Unicode characters. It is human understandable. Python programs,
contents written in text editors are example of text files. Its Extension is .txt
  2. BINARY FILE
A binary file stores the data in the same way as as stored in the memory that is in binary
or machine language code (0,1). It is not human understandable. The .exe files, mp3
file, image files, word documents are examples. Its Extension is .dat
  3. CSV FILE
A file whose contents are seperated by commas. It stores its content into Tabular form
for easy reading and accesing. Its Extension is .csv
                              FILE MODES
r    Opens a file in read mode. If file does not exists, it gives an error “File not Found”.
     Opens a file in write mode. If file does not exists, it creates a new file.It
W    overwrites the file if the file exists.
     Opens a file in append mode. It adds a new record at the end in existing
a    file. IfIt is used when we wand read and write in same file. file does not
     exists, it creates a new file.
     Opens a file in read and write mode. It is used when we wand read and write in
r+   same file.
     Opens a file in write and read mode. If file does not exists, it creates a
W+   new file.It overwrites the file if the file exists. It is used when we want
     read and write in same file.
     Opens a file in append mode. It adds a new record at the end in existing file.
a+   It is used when we wand read and write in same file.
            READ FUNCTION IN TEXT FILE
●
    1. READ CHARACTER BY CHARCTER-→ using read function
      def countspace():
      f = open (“Country.txt”, “r”)
      c=0
      r = f.read()
      for i in r:
        if i== “ ” :
           c=c+1
      f.close()
      print (c)
          READ FUNCTION IN TEXT FILE
2. READ WORDS-→ using read and split function
   def COUNT_AND( ):
    count=0
    file=open(‘STORY.TXT','r')
    line = file.read()
    word = line.split()
    for w in word:
    if w ==’AND’:
    count=count+1
    print(count)
    file.close()
Readline / Readlines FUNCTION IN TEXT FILE
READLINES-→read all         READLINE-→ read one line at a time
lines at a time and make
a list of these lines.         def filter(oldfile, newfile):
                                f1 = open("oldfile","r")
 def count_lines( ):            f2 = open(“newfile”,”w”)
  c=0                           while True:
  f = open("MyNotes.txt")       text= f1.readline()
  line = f.readlines()          if len(text) ==0:
  for w in line:                break
  if w[0] == 'G':               if text[0] == ‘@’:
  print(w)                      continue
  f.close()                     f2.write(text)
                                f1.close()
                                f2.close()
           READ AND WRITE IN BINARY FILE.
                                import pickle
●
    Create a binary file        Rec=[]
    student.dat to hold         def studentwrite():
    students’ records like        f=open("student.dat","wb")
    Rollno, name, and Address     rno = int(input("Enter Student No:"))
    using the list. Write         sname = input("Enter Student Name:")
    functions to write data,      address = input("Enter Address:")
    read them, and print.         rec=[rno,sname,address]
                                  pickle.dump(rec,f)
                                  f.close()
                                def studentread():
                                  f = open("student.dat","rb")
                                  rec=pickle.load(f)
                                  for i in rec:
                                     print(i)
def search_rec():
  f = open("sales.dat","rb")
  s=int(input("Enter id to search:"))
                                        SEARCH IN
  f1 = 0
  try:
                                        BINARY FILE.
      while True:
         d = pickle.load(f)
         if d["SalesId"]==s:
             f1=1
             print(d)
             break
  except Exception:
      f.close()
  if f1==0:
      print("Record not found...")
  else:
      print("Record found...")
import csv
def pro4():
#Create Header First
                                              WRITE IN CSV FILE
f = open(“students.csv”,”w”)
dt = writer(f)
dt.writerow([‘Student_ID’,’StudentName’,’Score’])
f.close()
#Insert Data
f = open(“students.csv”,”a”)
while True:
st_id= int(input(“Enter Student ID:”))
st_name = input(“Enter Student name:”)
st_score = input(“Enter score:”)
dt = writer(f)
dt.writerow([st_id,st_name,st_score])
ch=input(“Want to insert More records?(y or Y):”)
ch=ch.lower()
if ch !=’y’:
break
print(“Record has been added.”)
f.close()
READ FROM CSV FILE
import csv
with open(‘students.csv’”) as f:
data = csv.Reader(f)
print(“Student Name”,”\t”, “Score”)
for i in data:
print(i[‘StudentName’] ,i[‘Score’])