How to while-loop .readline see str in the file

Hello,

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 !=?

Thank you in advance.

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.

2 Likes

A file is a line iterator. Use str.rstrip to remove any whitespace, including newlines, at the end of a string.

for row in file:
    row = row.rstrip()
   <continue processing row>

Use strip to also remove whitespace at beginning.
Use if row[-1] == '\n': row = row[:-1] to only remove a newline.

2 Likes

So, the "" referred in if row == "": is that the last nonexistent/ empty row has no \n,\t etc. at the end, not that the line is empty?

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.

1 Like

So, now the code works, but is shows
if row[-1] == “\n”:
IndexError: string index out of range

file = open ('text.txt', "r")
while True:
    row = file.readline()
    if row[-1] == "\n":
        row = row[:-1]    
        if row == "":
            break
      #elif... etc

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")
1 Like

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.

Ahum, there was an error, as I wrote above.

if row[-1] == "\n": asks whether the last character of row is a newline, but when you reach the end of the file, row will be "".

What is the last character of an empty string? There isn’t one.

1 Like

Thank you. It works now. I needed to have it this way:

while (True):
    if row = "":
        break
    elif row [-1] = '\n':
        row = row [:-1]
        if # etc.
        elif #etc:    

I had to arrange the hierarchy of some rows.