Jono Jono - 1 year ago 69
Python Question

In Python, how can I get a line number corresponding to a given character location?

If I have a text that I've read into memory by using

, and if I know a certain location in this file, say, at character 10524, how can I find the line number of that location?

mkj mkj
Answer Source

Something along the lines of:

txt = open('myfile.txt').read()
lineno = len([c for c in txt[:10524] if c == '\n'])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download