2

Python's built-in open function returns a "file-like object". These file objects can be obtained in other ways as well, and may not actually represent files.

I haven't been able to find what I want to know about these.

https://docs.python.org/3/glossary.html#term-file-object states that all file objects all have 1 thing in common: they expose "a file-oriented API". But I can't find any documentation about this api.

A file object's write method seems to return an integer, but what does it represent? Is the return value guaranteed to be an integer? What methods and properties are file objects guaranteed to have?

2
  • I believe it returns the number of bytes written, you could look at the documentation for write to verify. But I don't know of any documentation specifically for generic file-like objects. Commented Oct 17, 2019 at 2:34
  • I was never able to find any documentation for write in the anywhere in the Python/C API Reference Manual. However, after your comment, I decided to try again, and looked through the The Python Tutorial this time. I was able to find a little documentation about write and what it returns in The Python Tutorial, here: docs.python.org/3/tutorial/… . (It says it "returns the number of characters written".) Commented Oct 17, 2019 at 16:18

1 Answer 1

3

People are so unlikely to use the return value of write that I wouldn't be surprised if any particular file-like object just returned None. That said, there is something resembling a spec.

The behavior a file-like object's methods should provide is documented in the io module docs, under the abstract base classes. While many file-like objects will not be instances of those ABCs, and many file-like objects will not provide all methods in the nearest ABC, methods they do provide should match the ABC docs.

For a binary file-like object, write should return the number of bytes written, as documented under RawIOBase.write.

For a text file-like object, write should return the number of characters written, as documented under TextIOBase.write.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.