X33
X33

Reputation: 1410

Python check if file object is in write mode

Is there a quick "pythonic" way to check if a file is in write mode, whether the mode is r+, w, w+, etc. I need to run a function when __exit__ is called, but only if the file is open in write mode and not just read-only mode. I am hoping some function exists to obtain this information but I can't seem to find anything.

Is there a way to do this without having to build a separate function to interpret the list of mode types?

Upvotes: 1

Views: 2042

Answers (2)

Semen
Semen

Reputation: 120

I use os.access('your_file_path', os.W_OK) to check write mode.

file.mode always returns 'r', while the file is actually in 'write' mode.

Upvotes: 0

Chen A.
Chen A.

Reputation: 11280

Simply by using file.mode attribute

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

Upvotes: 2

Related Questions