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'