How to Check if a File is Opened for Writing or Reading in Python

To determine whether a file is open for writing, reading, or appending in Python, you can use the mode attribute.

filename.mode

The mode attribute indicates the access mode of the file.

  • 'w' for writing
  • 'r' for reading
  • 'a' for appending

Note: If the file is not open, the mode attribute will return the mode of the last access and will not raise an error. Therefore, it’s important to verify if the file is currently open or closed using the closed attribute before proceeding.

Examples

Example 1

>>> f = open('test.txt', 'w')
>>> f.mode

The mode attribute returns 'w' because the file is open for writing.

'w'

Example 2

>>> f = open('test.txt', 'r')
>>> f.mode

The mode attribute returns 'r' because the file is open for reading.

'r'

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Managing Files in Python