0
with open("text.txt") as f:
       for line in f:
         line.isalpha()
 
False

File has only one line and contents are: "abc"

  • 4
    check for newline and space characters at the end of the line. line.strip().isalpha() should return True – darth baba Jul 08 '21 at 12:55
  • yeah, wow! It gives 'true'. Why strip()? Do we need to strip even if there's only 1 line in a file? – Muhammad Idrees Hassan Jul 08 '21 at 12:58
  • There is not only one line in your file. `strip()` will remove all whitespaces at beginning and end of the line, so also removing newlines. A file without a newline at the end will return `True` – Ocaso Protal Jul 08 '21 at 13:00

3 Answers3

0

I think this is because there is a space after the "abc" content

Gaston
  • 185
  • 7
0

As far as I know file lines are usually terminated by newline character \n which is the answer why isalpha() returns false.

0

As the others pointed out, it must be for some other characters in the file; likely either "\n" for line termination, or some others.

In brief, you want to remove those characters. Try:

line.strip().isalpha()

Full explanation below.

Load data:

with open("text.txt") as f:
       for line in f:
         line.isalpha()

The output of line is:

>>> line
'abc\n'

And of course the result of isalpha() is false:

>>> print(line.isalpha())
False

However, removing the \n you obtain the correct result:

>>> line.strip()
'abc'
>>> line.strip.isalpha()
True

(To troubleshoot this, you may want to just output the line in the interpreter, without print statements, otherwise you won't see special characters as '\n')

luco00
  • 501
  • 5
  • 9