2

I have a text file "numbers.txt" which contains a single line :

1

To determine whether this string is a digit or not I am doing this :

>>> fr = open("number.txt","r")
>>> line = fr.open()
>>> print line,type(line)
1
<type 'str'>

which is correct but then, when I do this,

>>> line.isdigit()
False

I have checked the following too:

>>> '1'.isdigit()
True

So why can't be it, when I read it from file?

Thanks in advance for any ideas and solutions.

niladri chakrabarty
  • 503
  • 1
  • 7
  • 15
  • Well `fr.open()` should probably be `.readline()` - else that'll error.... And *all* characters need to be digits - when reading from a file, it including the line terminator so `'1\n'.isdigit()` is false... strip the line `line.strip().isdigit()` – Jon Clements Feb 02 '15 at 08:04
  • Related: http://stackoverflow.com/q/354038/1025391 – moooeeeep Feb 02 '15 at 08:28
  • Thanks :) . Solved. Actually I created the text file "numbers.txt" from command line (echo "1" > numbers.txt) . So I thought there should not be any other character ('\n' or ' '). But yes, readline() does that kind of mischief. It adds the newline character at the end of the line. – niladri chakrabarty Feb 02 '15 at 09:15

1 Answers1

2

It's because your file contains new lines or other whitspaces. You can strip your file after read , ( Note that this is for when you are sure that your file is contain one character ) :

fr = open("number.txt","r").read()
fr.strip().isdigit()

if you have other lines you can go through lines :

 with open("number.txt","r") as f :
    for line in f :
        print f.strip().isdigit()
Mazdak
  • 105,000
  • 18
  • 159
  • 188