1

I have a file that has many lines, the first four lines start with some letters (a word) and the rest start with a number. I want to iterate over the lines that start with a number (three-digit number, eg '123' followed by different variables containing both letters and numbers) and ignore the first 4 lines. This is what I have done, but it gives me a blank list in an output.

number = []  
for line in infile.readline():  
    line = line.rstrip()  
    if line.startswith('[0-9]'):
        number.append(line.split()[0])  
print number

Why is the 'number' list empty in my output?

This is what the infile looks like:

Value = 152  
Numb = 0.005  
Pos = 75  
Samp = 12.5  
150    K    0.345  
234    T    0.764  
565    X    0.345 
4

2 回答 2

5

因为startswith需要一个字符串,而不是正则表达式。你想要re.match

编辑:或import string; line.startswith(tuple(string.digits))(感谢@GarethRees)

于 2012-12-03T16:17:24.817 回答
1

不是直接的答案,但最简单的跳过行的方法是:

from itertools import islice
with open('file') as fin:
    for line in islice(fin, 4, None):
        pass # do something
于 2012-12-03T16:23:13.113 回答