Python Forum
testing an open file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: testing an open file (/thread-38991.html)



testing an open file - Skaperen - Dec-17-2022

what kind of test can i apply (or what library should i look at) to be able to detect if a given open file is open for reading? it is passed as an argument to a function so the function does get to directly see how the file was opened.


RE: testing an open file - Larz60+ - Dec-17-2022

you can get the mode (and much more) by using stats

for example (run from script path -- modify path as required --, probably better to use pathlib):
modified from example here: https://docs.python.org/3/library/os.html#os.scandir
import os

path = os.getcwd()
with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            stats = os.stat(path, follow_symlinks=False)
            print(stats)
see https://docs.python.org/3/library/stat.html on how to interpret the stat results.


RE: testing an open file - Gribouillis - Dec-17-2022

If the file was opened with the builtin function open(), it may have a mode attribute
>>> f = open('temp.tex')
>>> f.mode
'r'



RE: testing an open file - Skaperen - Dec-17-2022

i was wanting how it was opened, not what permissions the file allows me to open. it might be open to a non-file object like:
Output:
lt1a/forums/3 /home/forums 4> python3.8 Python 3.8.10 (default, Nov 14 2022, 12:59:47) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdin.mode,sys.stderr.mode,sys.stdout.mode ('r', 'w', 'w') >>> lt1a/forums/3 /home/forums 5>
what cases where it may not have a mode attribute?


RE: testing an open file - Gribouillis - Dec-17-2022

(Dec-17-2022, 06:47 PM)Skaperen Wrote: what cases where it may not have a mode attribute?
When the (pseudo) file object was not opened by the function open(), for example
>>> import io
>>> f = io.StringIO()
>>> f.mode
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_io.StringIO' object has no attribute 'mode'



RE: testing an open file - Skaperen - Dec-19-2022

it's an open file object. i want to see if i can read it without trying to read it. i think i might need the same for write.


RE: testing an open file - Gribouillis - Dec-19-2022

Objets subclassing io.IOBase have a .readable() method. This also applies to StringIO.

Pseudo file objects provided by third party code may have no readable() or writable() method.


RE: testing an open file - Skaperen - Dec-20-2022

so, i can just test for mode or a method and if neither exist, just raise an exception saying that readability cannot be determined. that should be workable for most common cases, i think. or am i guessing too far?