简体   繁体   English

如何在Python中查找光标的行号?

[英]How to find line number of cursor in Python?

I am reading a file in Python. 我正在用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. Python本身只跟踪你在字节方面的距离,并且无法根据行号移动。

Edit: I stand corrected. 编辑:我纠正了。 S.Lott's suggestion of fileinput is spot on. fileinput关于fileinput的建议是现货。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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