File handling in python

File input and output:

  • File handling is a mechanism by which we can read data off disk files in python program or write back data from python program to disk files.
  • So far in our python program the standard input is coming from the keyboard and output is going to monitor i.e. no where data is stored permanently and entered data is present as long as program is running but file handling allows us to store data entered through python program permanently in a disk file and later on we can read back the data.
  • The data files can be stored in two ways

          1. Text File

          2. Binary File

Steps in Data File Handling:

1. OPENING FILE

  • The file can be opened for either – read, write, append.
  • The default mode is “read”.

  1. Syntax:

    Variable_name = open(filename,mode)

    or

    Variable_name = open(file_path,mode)

    Example:

    f=open("student.txt",r) #open a file from python download path

    or

    f=open("D:\\KURSHITHA\\WHEREISSTUFF\\student.txt",r) #open a file from custom path

View current path for created files or viewing create files where are stored in python:

  1. #Getting name of current working directory

    import os

    pwd = os.getcwd()

    print("Current Directory :",pwd)

Output:

2. PERFORMING READ/WRITE/APPEND

  • Once the file is opened now we can either read or write for which file is opened using various functions available.

3. CLOSING FILE

  • After performing the operation we must close the file and release the file for other applications to use it.

  1. Syntax:

              File_variable_name.close()

    Example:

              f.close()

Text File handling:

Write any data into the file using file handling:

  1. #write enterd details onto the file

    f=open("book.txt","w")

    ans='y'

    while ans=='y':

        bno=int(input("Enter book number:"))

        bname=input("Enter book name:")

        author=input("Enter Author Name:")

        price=int(input("Enter book price:"))

        brec=str(bno) + "." + bname + "," + author + "," + str(price) + "\n"

        f.write(brec)

        ans=input("Add more records?")

    f.close()

Output:


Append any data into the file using file handling:

  1. #write entered details onto the file using append

    f=open("book.txt","a")

    ans='y'

    while ans=='y':

        bno=int(input("Enter book number:"))

        bname=input("Enter book name:")

        author=input("Enter Author Name:")

        price=int(input("Enter book price:"))

        brec=str(bno) + "." + bname + "," + author + "," + str(price) + "\n"

        f.write(brec)

        ans=input("Add more records?")

    f.close()

Output:


Read data from the file using file handling:

  1. #Reading line by line using readline()

    f = open("book.txt","r")

    str=" "

    while str:

        str=f.readline()

        print(str,end='')

    f.close()

    #Reading line by line using for loop

    f = open("book.txt","r")

    for i in f:

        print(i)

Output:

To copy the content of one file to another file:

  1. f1=open("book.txt","r")

    f2=open("book_copy.txt","w")

    str1=" "

    while str1:

        str1=f1.readline()

        f2.write(str1)

    f1.close()

    f2.close()

    print("copied successfully...")

Output:


with statement:

  • Python’s “with” statement for the file handling is very handy when you have two related operations which you would like to execute as a pair, with a block of code in between:
Syntax:
  1. with open(filename[, mode]) as filehandle:

              file_manipulation_statement

  • The advantage of “with” is it will automatically close the file after the nested block of code.
  • It guarantees to close the file how nested block exits even if any run time error occurs.

Example program:

  1. with open("text_document.txt","w") as f:

        f.write("Welcome to file handling")

    print("Data successfully inserted in text file...")

Output:



Binary file operations:

  • The binary file is nothing but, It is used to convert normal text file into an unreadable format using pickle module in python.

Pickle:

  • Pickling is the process of converting structure to a byte stream before writing to a file and while reading the content of file a reverse process called Unpickling is used to convert the byte stream back to the original format.

Steps to perform binary file operations:

Step 1: First we need to import the module called pickle.

Step 2: This module provides 2 main functions:

1. dump() : to write the object in the file which is loaded in binary mode

          Syntax : dump(object_to_write, filehandle)

2. load() : dumped data can be read from a file using load() i.e. it is used to read object from pickle file.

Step 3: Close the file.

Example program:

  1. import pickle

    myfile=open("text_document.txt","wb")

    dict={'Name':'Kurshitha','Gender':'Female','Age':22}

    pickle.dump(dict,myfile)

    print("Data sucessfully inserted in test file...")

    myfile.close()

    mf=open("text_document.txt","rb")

    dict=pickle.load(mf)

    print("Data from file:",dict)

    mf.close()

Output:

Share:

No comments:

Post a Comment

Popular Posts

Search This Blog

Powered by Blogger.

Service Support

Need our help to Learn or Post New Concepts Contact me

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me