Jono Jono - 2 months ago 6
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

open('myfile.txt').read()
, 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

Something along the lines of:

txt = open('myfile.txt').read()
lineno = len([c for c in txt[:10524] if c == '\n'])
Comments