Python file modes | Open, Write, append (r, r+, w, w+, x, etc)

When you do work with the file in Python you have to use modes for specific operations like create, read, write, append, etc. This is called Python file modes in file handling.

Python file modes Open, Write, append

Python file modes

Don’t confuse, read about very mode as below.

  • r for reading – 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.
  • 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.
  • w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, it creates a new file for reading and writing.
  • rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file.
  • rb+ Opens a file for both reading and writing in binary format.
  • 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, it 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.
  • x open for exclusive creation, failing if the file already exists (Python 3)

See basic Example of use File mode

Create File

More Examples of create a file: Python Create File (Empty Text File)

Write File

Now writing the file. w – Write mode

Python File Handling Quiz

Python File Handling to test your knowledge – ( Create, Open, Update, delete and more about in Python)
It’s for Beginners, Advanced and Experienced Programmers.

Do comment if you have any doubts and suggestions on this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.