I have this exercise, in where a text file is read line by line. The part I fail to understand is below.
while (True):
row = file.readline()
if row == "" #here the variable row is recognised. Interestingly here is also "" which to me means that Python sees that part as str, no?
break
elif row.isdigit(): # this does not work, the variable row is not recognised as bringing str.
print("The row is only numbers")
else:
print("Something went wrong.")
I encounter this issue that only else: activates, possibly due to file.readline() not being interpeted as str.
This below works:
word = "1234"
if str(word).isdigit() == True:
print("Only numbers here.")
The below one does not work because .isdigit() works only with str and not with int.
word = 1234 # this part here needs to be with "" because now 1234 is seen as a variable, right?
if str(word).isdigit() == True:
print("Only numbers here.")
So my question is, how can I make Python see row=file.readline() as a str so that I can create comparisons using == and !=?
file.readline() reads a line. That’s always a string. The line will usually end with "\n", although the last line might not. At the end of the file, it’ll return "".
What I suspect is happening is that row is a line ending with "\n", e.g. "1234\n", and that "1234\n".isdigit() is returning False, which is correct as it’s not all digits.
Exactly. When there’s no more data left in the (text) file, further attempts to read from it return the empty string. If the last line has no "\n" at the end then the final readline call returns a string with no newline. If it does have the "\n", that is included. In either case the file is now exhausted, and further reads will return the empty string.
Great. Now you’ve worked out the logic for yourself, you might also want to experiment with iterating over the file, which is a very convenient way to process each line in a text file. When you use an open file in a for statement, each iteration returns the next line from the file (i.e., what readline would have returned):
for row in file:
if row.strip().isdigit():
print("The row is only numbers")
else:
print("Something went wrong")
Not at all. Working out the correct traditional logic to handle a text file like you did is a significant achievement for a learner. That was the way we all had to do it for about the first twelve years of Python’s existence! At the same time, now there are simpler ways you probably want to use them.