FILE HANDLING  INTRODUCTION  DATA FILES  OPENINGANDCLOSING FILES  READINGANDWRITING FILES  STANDARD INPUT,OUTPUTAND ERRORSTREAMS
Introduction  FILE HANDLING is a mechanism by which we can read data of disk files in python program or write back data from python program to disk files.  So far in our python program the standard input in coming from keyboard an output is going to monitor i.e. no where data is stored permanent 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 disk file and later on we can read back the data
DATA FILES  It contains data pertaining to a specific application, for later use. The data files can be stored in two ways –  Text File  Binary File
Text File  Text file stores information in ASCII OR UNICODE character. In text file everything will be stored as a character for example if data is “computer” then it will take 8 bytes and if the data is floating value like 11237.9876 it will take 10 bytes.  In text file each like is terminated by special character called EOL. In text file some translation takes place when this EOL character is read or written. In python EOL is ‘n’ or ‘r’ or combination of both
Binary files  It stores the information in the same format as in the memory i.e. data is stored according to its data type so no translation occurs.  In binary file there is no delimiter for a new line  Binary files are faster and easier for a program to read and write than text files.  Data in binary files cannot be directly read, it can be read only through python program for the same.
Steps in Data File Handling 1. OPENING FILE  We should first open the file for read or write by specifying the name of file and mode. 2. PERFORMING READ/WRITE  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 operation we must close the file and release the file for other application to use it,
Opening File  File can be opened for either – read, write, append. SYNTAX: file_object = open(filename) Or file_object = open(filename,mode) ** default mode is “read”
Opening File myfile = open(“story.txt”) here disk file “story.txt” is loaded in memory and its reference is linked to “myfile” object, now python program will access “story.txt” through “myfile” object. here “story.txt” is present in the same folder where .py file is stored otherwise if disk file to work is in another folder we have to give full path.
Opening File myfile = open(“article.txt”,”r”) here “r” is for read (although it is by default, other options are “w” for write, “a” for append) myfile = open(“d:mydatapoem.txt”,”r”) here we are accessing “poem.txt” file stored in separate location i.e. d:mydata folder. at the time of giving path of file we must use double backslash() in place of single backslash because in python single slash is used for escape character and it may cause problem like if the folder name is “nitin” and we provide path as d:nitinpoem.txt then in nitin “n” will become escape character for new line, SO ALWAYS USE DOUBLE BACKSLASH IN PATH
Opening File myfile = open(“d:mydatapoem.txt”,”r”) another solution of double backslash is using “r” before the path making the string as raw string i.e. no special meaning attached to any character as: myfile = open(r“d:mydatapoem.txt”,”r”)
File Handle myfile = open(r“d:mydatapoem.txt”,”r”) In the above example “myfile” is the file object or file handle or file pointer holding the reference of disk file. In python we will access and manipulate the disk file through this file handle only.
File Access Mode Text File Mode Binary File Mode Description Notes ‘r’ ‘rb’ Read only File must exists, otherwise Python raises I/O errors ‘w’ ‘wb’ Write only If file not exists, file is created If file exists, python will truncate existing data and overwrite the file. ‘a’ ‘ab’ Append File is in write mode only, new data will be added to the end of existing data i.e. no overwriting. If file not exists it is created ‘r+’ ‘r+b’ or ‘rb+’ Read and write File must exists otherwise error is raised Both reading and writing can take place w+ ‘w+b’ or ‘wb+’ Write and read File is created if not exists, if exists data will be truncated, both read and write allowed ‘a+’ VINOD K SAC ‘a+b’ or ‘ab+’ UMARVERMA,PGT(CS), HIN BHARDWAJ, PGT(CS) Write and read KV OEF KANPUR& , KV NO.1TEZPUR Same as above but previous content will be retained and both read and write.
Closing file  As reference of disk file is stored in file handle so to close we must call the close() function through the file handle and release the file. myfile.close() Note: open function is built-in function used standalone while close() must be called through file handle
Reading from File  To read from file python provide many functions like :  Filehandle.read([n]) : reads and return n bytes, if n is not specified it reads entire file.  Filehandle.readline([n]) : reads a line of input. If n is specified reads at most n bytes. Read bytes in the form of string ending with line character or blank string if no more bytes are left for reading.  Filehandle.readlines(): reads all lines and returns them in a list
Example-1: read() SAMPLE FILE
Example-2: read() SAMPLE FILE
Example-3: readline() SAMPLE FILE
Writing onto files  After read operation, let us take an example of how to write data in disk files. Python provides functions:  write ()  writelines()  The above functions are called by the file handle to write desired content. Name Syntax Description write() Filehandle.write(str1) Writes string str1 to file referenced by filehandle Writelines() Filehandle.writelines(L) Writes all string in List L as lines to file referenced by filehandle.
Example-1: write() using “w” mode
Example-1: write() using “w” mode Lets run the same program again
Example-1: write() using “w” mode Now we can observe that while writing data to file using “w” mode the previous content of existing file will be overwritten and new content will be saved. If we want to add new data without overwriting the previous content then we should write using “a” mode i.e. append mode.
Example-2: write() using “a” mode New content is added after previous content
Example-3: using writelines()
Example-4: Writing String as a record to file
Example-5: To copy the content of one file to another file

FILE HANDLING in python to understand basic operations.

  • 1.
    FILE HANDLING  INTRODUCTION DATA FILES  OPENINGANDCLOSING FILES  READINGANDWRITING FILES  STANDARD INPUT,OUTPUTAND ERRORSTREAMS
  • 2.
    Introduction  FILE HANDLINGis a mechanism by which we can read data of disk files in python program or write back data from python program to disk files.  So far in our python program the standard input in coming from keyboard an output is going to monitor i.e. no where data is stored permanent 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 disk file and later on we can read back the data
  • 3.
    DATA FILES  Itcontains data pertaining to a specific application, for later use. The data files can be stored in two ways –  Text File  Binary File
  • 4.
    Text File  Textfile stores information in ASCII OR UNICODE character. In text file everything will be stored as a character for example if data is “computer” then it will take 8 bytes and if the data is floating value like 11237.9876 it will take 10 bytes.  In text file each like is terminated by special character called EOL. In text file some translation takes place when this EOL character is read or written. In python EOL is ‘n’ or ‘r’ or combination of both
  • 5.
    Binary files  Itstores the information in the same format as in the memory i.e. data is stored according to its data type so no translation occurs.  In binary file there is no delimiter for a new line  Binary files are faster and easier for a program to read and write than text files.  Data in binary files cannot be directly read, it can be read only through python program for the same.
  • 6.
    Steps in DataFile Handling 1. OPENING FILE  We should first open the file for read or write by specifying the name of file and mode. 2. PERFORMING READ/WRITE  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 operation we must close the file and release the file for other application to use it,
  • 7.
    Opening File  Filecan be opened for either – read, write, append. SYNTAX: file_object = open(filename) Or file_object = open(filename,mode) ** default mode is “read”
  • 8.
    Opening File myfile =open(“story.txt”) here disk file “story.txt” is loaded in memory and its reference is linked to “myfile” object, now python program will access “story.txt” through “myfile” object. here “story.txt” is present in the same folder where .py file is stored otherwise if disk file to work is in another folder we have to give full path.
  • 9.
    Opening File myfile =open(“article.txt”,”r”) here “r” is for read (although it is by default, other options are “w” for write, “a” for append) myfile = open(“d:mydatapoem.txt”,”r”) here we are accessing “poem.txt” file stored in separate location i.e. d:mydata folder. at the time of giving path of file we must use double backslash() in place of single backslash because in python single slash is used for escape character and it may cause problem like if the folder name is “nitin” and we provide path as d:nitinpoem.txt then in nitin “n” will become escape character for new line, SO ALWAYS USE DOUBLE BACKSLASH IN PATH
  • 10.
    Opening File myfile =open(“d:mydatapoem.txt”,”r”) another solution of double backslash is using “r” before the path making the string as raw string i.e. no special meaning attached to any character as: myfile = open(r“d:mydatapoem.txt”,”r”)
  • 11.
    File Handle myfile =open(r“d:mydatapoem.txt”,”r”) In the above example “myfile” is the file object or file handle or file pointer holding the reference of disk file. In python we will access and manipulate the disk file through this file handle only.
  • 12.
    File Access Mode Text File Mode BinaryFile Mode Description Notes ‘r’ ‘rb’ Read only File must exists, otherwise Python raises I/O errors ‘w’ ‘wb’ Write only If file not exists, file is created If file exists, python will truncate existing data and overwrite the file. ‘a’ ‘ab’ Append File is in write mode only, new data will be added to the end of existing data i.e. no overwriting. If file not exists it is created ‘r+’ ‘r+b’ or ‘rb+’ Read and write File must exists otherwise error is raised Both reading and writing can take place w+ ‘w+b’ or ‘wb+’ Write and read File is created if not exists, if exists data will be truncated, both read and write allowed ‘a+’ VINOD K SAC ‘a+b’ or ‘ab+’ UMARVERMA,PGT(CS), HIN BHARDWAJ, PGT(CS) Write and read KV OEF KANPUR& , KV NO.1TEZPUR Same as above but previous content will be retained and both read and write.
  • 13.
    Closing file  Asreference of disk file is stored in file handle so to close we must call the close() function through the file handle and release the file. myfile.close() Note: open function is built-in function used standalone while close() must be called through file handle
  • 14.
    Reading from File To read from file python provide many functions like :  Filehandle.read([n]) : reads and return n bytes, if n is not specified it reads entire file.  Filehandle.readline([n]) : reads a line of input. If n is specified reads at most n bytes. Read bytes in the form of string ending with line character or blank string if no more bytes are left for reading.  Filehandle.readlines(): reads all lines and returns them in a list
  • 15.
  • 16.
  • 17.
  • 18.
    Writing onto files After read operation, let us take an example of how to write data in disk files. Python provides functions:  write ()  writelines()  The above functions are called by the file handle to write desired content. Name Syntax Description write() Filehandle.write(str1) Writes string str1 to file referenced by filehandle Writelines() Filehandle.writelines(L) Writes all string in List L as lines to file referenced by filehandle.
  • 19.
  • 20.
    Example-1: write() using“w” mode Lets run the same program again
  • 21.
    Example-1: write() using“w” mode Now we can observe that while writing data to file using “w” mode the previous content of existing file will be overwritten and new content will be saved. If we want to add new data without overwriting the previous content then we should write using “a” mode i.e. append mode.
  • 22.
    Example-2: write() using“a” mode New content is added after previous content
  • 23.
  • 24.
    Example-4: Writing Stringas a record to file
  • 25.
    Example-5: To copythe content of one file to another file