Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current open file line in python?

Suppose you open a file, and do an seek() somewhere in the file, how do you know the current file line ?

(I personally solved with an ad-hoc file class that maps the seek position to the line after scanning the file, but I wanted to see other hints and to add this question to stackoverflow, as I was not able to find the problem anywhere on google)

like image 584
Stefano Borini Avatar asked Nov 27 '09 14:11

Stefano Borini


People also ask

How do I show a file line in Python?

Load the text file into the python program to find the given string in the file. Ask the user to enter the string that you want to search in the file. Read the text file line by line using readlines() function and search for the string. After finding the string, print that entire line and continue the search.

What does open () read () do in Python?

Python has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. We can specify the mode while opening a file. In mode, we specify whether we want to read r , write w or append a to the file.

What does read () do in Python?

read() method in Python is used to read at most n bytes from the file associated with the given file descriptor. If the end of the file has been reached while reading bytes from the given file descriptor, os. read() method will return an empty bytes object for all bytes left to be read.


1 Answers

When you use seek(), python gets to use pointer offsets to jump to the desired position in the file. But in order to know the current line number, you have to examine each character up to that position. So you might as well abandon seek() in favor of read():

Replace

f = open(filename, "r")
f.seek(55)

with

f = open(filename, "r")
line=f.read(55).count('\n')+1
print(line)

Perhaps you do not wish to use f.read(num) since this may require a lot of memory if num is very large. In that case, you could use a generator like this:

import itertools
import operator
line_number=reduce(operator.add,( f.read(1)=='\n' for _ in itertools.repeat(None,num)))
pos=f.tell()

This is equivalent to f.seek(num) with the added benefit of giving you line_number.

like image 186
unutbu Avatar answered Sep 21 '22 08:09

unutbu