简体   繁体   中英

What's the easiest way to iterate on a file's lines, keeping a counter?

What's the cleanest code that iterates on the lines of a text file, while simultaniously increamenting a counter?

I understand that with multiple assignment, there's a cleaner syntax than

i = 0
for line in f:
    ...
    ++i
for i, line in enumerate(f):
  print i, line

As seen here: http://docs.python.org/library/functions.html#enumerate

for count, line in enumerate(f):

Enumerate starts at index 0 unless told otherwise providing a counter iterated at the same time as each item of your for loop

EDIT: As a side note you can change where enumerate starts from with the second argument eg for count, line in enumerate(f, 11) would cause it to start at 11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM