File Handling in Python

 We were using variables to store the data till now. But in case the program completes, values get destroyed. If we want to store data persistently then file is the solution.

File is stored in secondary storage such as hard disk, SSD, pen drive etc.

Types of files

  • Binary files - Image, Audio/Video, pdf, MP3/4 etc.
  • Text files
Steps in file handling

  • Open a file
  • Read a file/Write (Perform Operation)
  • Close a file
Internally if we are opening a file, a copy of same is loaded in RAM and once the modification is completed and saved, we are making a change persistently in storage. 


Before opening file, we need to express intention using opening modes

File Opening Modes

r - Intention is to read, if file is not found then raise FileNotFoundError Exception
w - Intention is to write in a file, if files already exist then erase the content, if not create a new file
a - Append a data to a file at the end, if file doesn't exist then create a new
r+ - read and write, error if file is not found
w+ - write and read, if file is not present create a new, erase if present
a+ - Append data to file at last if present, else create a new content

#writing in a file
def writing(filename,text):
    f = open(filename,'w')
    f.write(text)
    f.close()
def append(filename,text):
    f = open(filename,'a')
    f.write(text)
    f.close()
# writing('file1.txt','This is sample text')
append('file1.txt','\nSome extra text')
#reading a file
def reading(filename):
    try:
        f = open(filename,'r')
        text = f.read()
        print(text)
        f.close()
    except FileNotFoundError:
        print('File not found')
reading('file2.txt')


def search(filename,word):
    try:
        f = open(filename,'r')
        linecount=0
        for line in f.readlines():
                #readlines will return iterable with line
            linecount+=1
            strlist = line.split(' ')
            word_count = 0
            for w in strlist:
                     word_count+=1
                     if (w == word or w== word +'\n'):
                         f.close()
                         return (linecount,word_count)                        
                     else:
                         f.close()
                         return None
           
    except FileNotFoundError:
        print('File Not Found')


If we want os to take care for close file then below syntax can be used

with open(filename,'mode') as f:
    f.read()
    f.write()

No exception handling will be required with this syntax.






Comments