File Handling

Steps are briefly mentioned below for File Handling. In File Handling we read and write to a file and perform all operations to file.


Steps.

1. We need to create new  file or open an existing file.
2. We give a name to a file for reference and define Mode for various operation. Once the file is created File Pointer is received for other file operations.
   
     Open file as : file_pointer=open("file name",Mode)


     Define File Mode as 

         R  - Read only
         R+ - Read and Write Mode
         W – Write only, Over write file, create new file if does not exist.
         W+ - Write and read
         A – Append mode, file is pointer is at beginning of file, Creates new file if does not exists.
         A+ Reading and Appending, file is pointer is at beginning of file, Creates new file if does not exists


3. If we want to read file we can use readlines() or readline() to read line by line  from file.



    file_pointer.readline()     - This will read data from file. File is opened in r mode.



4. To write to file we use write() statement.



     file_pointer.write(string)



5. Finally close the file once all operations are performed.



    file_pointer.close()            - Close file once all operations are performed.


No comments:

Post a Comment