Can I use a list comprehension to get a sequential position of each non-blank line when reading in a file?

StackOverflow https://stackoverflow.com/questions/22564646

  •  18-06-2023
  •  | 
  •  

Domanda

I have been struggling how to create a list of tuples that have the line number and the line but I want to enumerate only non-blank lines

This gets me exactly what I want

counter = 0
line_list = []
for line in open(file).readlines()
    if line.strip() == '':
        continue
    line_list.append((counter,line.strip()))
    counter +=1

when I do this

line_list = [(index,line) for index, line in \
             enumerate(open(file).readlines() if line.strip() != 0]

as expected (after I thought about it) index advances for each line as it is read in so I get gaps in the numbers for every blank line read in

I also tried

counter = 0
line_list = [(counter,line) for line in open(file).readlines() \
            if line.strip != '' counter +=1]

this gives me a syntax error

Here is an example of the type of raw file

'Some words are in a line \n'
' maybe another line with more words\n'
'\n'
'\n'
'See the one or more blank lines\n'
'maybe more or less word\n'
'\n'
'\n'
'lots of lines with text\n'
È stato utile?

Soluzione

Enumerate just the non-empty lines:

[(index, line) for index,line in enumerate(l for l in open(file) if l.strip())]

Altri suggerimenti

line_list = list(enumerate(line for line in open(file) if line.strip()))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top