简体   繁体   中英

How to find line number of cursor in Python?

I am reading a file in Python. After I read a bunch of lines, is there a convenient function that I can use to get the current line number in the file that the cursor is on?

I am trying to refrain from using a counter since I have multiple functions that read the same file and may move the cursor all over the place.

Thanks

Something like enumerate ? There's is not really a "cursor" per say but the following will give you the current line number while reading a file line-by-line.

for i, line in enumerate(file):
    print i, line

You'll probably need to keep track of it separately, along with your file. You might wrap your file object to include a counter. Python itself only keeps track of how far along you are in terms of bytes, and has no way to move around based on line numbers.

Edit: I stand corrected. S.Lott's suggestion of fileinput is spot on.

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