Python Forum
what is being tested with this while ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
what is being tested with this while ?
#1
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)
Reply
#2
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?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
b'' is printed

Not sure what that represents in Python.
a NULL?
Reply
#4
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.
Reply
#5
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.
Reply
#6
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.
Reply
#7
Ah gotcha.

I still haven't found the location for the documentation of the read( ) method. Sigh.
Reply
#8
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/input...ting-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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020