Check if object is file-like in Python

后端 未结 8 833
抹茶落季
抹茶落季 2020-12-01 00:02

File-like objects are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of

8条回答
  •  佛祖请我去吃肉
    2020-12-01 00:24

    I ended up running into your question when I was writing an open-like function that could accept a file name, file descriptor or pre-opened file-like object.

    Rather than testing for a read method, as the other answers suggest, I ended up checking if the object can be opened. If it can, it's a string or descriptor, and I have a valid file-like object in hand from the result. If open raises a TypeError, then the object is already a file.

提交回复
热议问题