Python Forum
what is being tested with this while ? - 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: what is being tested with this while ? (/thread-36895.html)



what is being tested with this while ? - atexit8 - Apr-09-2022

I am new to Python but not other programming languages.

What is the condition being tested for in the while loop in the following snippet.
What is byte being compared to so that the condition is True?
Or to ask it another way, what happens to byte when the end of the file is reached?

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte:
        # Do stuff with byte.
        byte = f.read(1)



RE: what is being tested with this while ? - buran - Apr-09-2022

Truth value testing
(Apr-09-2022, 06:04 PM)atexit8 Wrote: Or to ask it another way, what happens to byte when the end of the file is reached?
did you do some tests e.g. print byte after exit the loop to see what you get?


RE: what is being tested with this while ? - atexit8 - Apr-09-2022

b'' is printed

Not sure what that represents in Python.
a NULL?


RE: what is being tested with this while ? - deanhystad - Apr-09-2022

Everything in Python can be treated as a bool. Nearly all Python objects are True. False, Null, 0 and empty collections are False. b"" is an empty bytes, so it is False.

When you write a class you can provide a __bool__() method that returns True or False for instances of the method.


RE: what is being tested with this while ? - atexit8 - Apr-09-2022

Are you saying that f.read(1) is returning a byte array and not just 1 byte?

I am trying to find out online the definition of the read( ) method.


RE: what is being tested with this while ? - deanhystad - Apr-09-2022

There is no such thing as a byte in Python. There are bytes, bytearrray and int. read() returns bytes, even if it is only one int in the bytes.


RE: what is being tested with this while ? - atexit8 - Apr-09-2022

Ah gotcha.

I still haven't found the location for the documentation of the read( ) method. Sigh.


RE: what is being tested with this while ? - deanhystad - Apr-09-2022

It is not hidden, but it can be partially hidden by the glut. I googled "python file read documentation" and this was at the very top of the list (for me).

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

Quote:To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode).

When looking for Python "documentation" I always add "documentation" to my query. When I don't, the search results are flooded with blogs and tutorials that mostly regurgitate the very basic same information.