Thursday, November 17, 2016

File handling in Python Cheatsheet: All modes

  • r

    Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
  • rb

    Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
  • r+

    Opens a file for both reading and writing. The file pointer will be at the beginning of the file. 
    (cannot truncate a file)
  • rb+

    Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.
  • w

    Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
  • wb

    Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
  • w+

    Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
    (can truncate a file)
  • wb+

    Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
  • a

    Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
  • ab 

    Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
  • a+

    Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
  • ab+

    Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.


Important


Always make sure you explicitly close each open file, once its job is done and you have no reason to keep it open. Because - There is an upper limit to the number of files a program can open. If you exceed that limit, there is no reliable way of recovery, so the program could crash. - Each open file consumes some main-memory for the data-structures associated with it, like file descriptor/handle or file locks etc. So you could essentially end-up wasting lots of memory if you have more files open that are not useful or usable. - Open files always stand a chance of corruption and data loss.




No comments:

Post a Comment