2

How can I only read lines in a file that start with numbers in python i.e

Hello World <--ignore
Lovely day
blah43 
blah
1234 <--read
blah12 <--ignore
blah 
3124 <--read
Not matter how many words there are <--ignore
blah 
0832 8423984 234892304 8239048324 8023948<--read
blah132 <--ignore
Jalcock501
  • 389
  • 2
  • 6
  • 18

2 Answers2

11
import re
with open("filename") as f:
    for line in f:
        if re.match(r"^\d+.*$",line):
            print line
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
vks
  • 67,027
  • 10
  • 91
  • 124
  • 1
    Edit to use [the `with` statement to open the file](http://www.youtube.com/watch?v=lRaKmobSXF4), as is best practice. – Gareth Latty Dec 17 '14 at 09:23
5

you can use isdigit() function :

for line in open('f.txt','r'):
   if line[0].isdigit():
       print line
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • Note that `isdigit()` has what might be a surprising definition of a digit, which may or may not be valid for the use case at hand. It includes all the numbers you would expect, but also [some unicode characters you might not](http://stackoverflow.com/questions/10604074/python-isdigit-function-return-true-for-non-digit-character-u-u2466). – Gareth Latty Dec 17 '14 at 09:24
  • isdigit is used for test that a string start with a number ? – Hacketo Dec 17 '14 at 09:25
  • @Hacketo When applied to the first character, as here, yes. – Gareth Latty Dec 17 '14 at 09:26
  • @Hacketo `isdigit()` Return true if all characters in the string are digits and there is at least one character, false otherwise – Mazdak Dec 17 '14 at 09:27