Working with txt files

A plain text file is used to store data that represents only characters or strings and doesn't consider any structured metadata. In Python, there's no need to import any external library to read and write text files. Python provides an built-in function to create, open, close, and write and read text files. To do the operations, there are different access modes to govern the type of operation possible in an opened file.

The access modes in Python are as follows:

  • Read Only Mode ('r'): This mode opens a text file for  the purpose. If that file doesn't exist, it raises an I/O error. We can also call this mode the default mode in which the file will open.
  • Read and Write Mode ('r+'): This mode opens a text file for reading as well as writing purposes and raises an I/O error if the file does not exist.
  • Write Only Mode ('w'): This mode will open a text file for writing. It creates the file if the file does not exist and, for existing file, the data is overwritten.
  • Write and Read Mode ('w+'):  This mode will open a text file for reading and writing. For the existing file, the data is overwritten.
  • Append Only Mode ('a'):  This mode will open a text file for writing. It creates the file if the file does not exist and the data will be inserted at the end of existing data.
  • Append and Read Mode ('a+'): This mode will open a text file for reading, as well as writing . It creates the file if the file does not exist and the data will be inserted at the end of the existing data. 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset