Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go to a specific line in Python?

Tags:

python

I want to go to line 34 in a .txt file and read it. How would you do that in Python?

like image 773
ArchHaskeller Avatar asked Mar 15 '10 01:03

ArchHaskeller


4 Answers

Use Python Standard Library's linecache module:

line = linecache.getline(thefilename, 33)

should do exactly what you want. You don't even need to open the file -- linecache does it all for you!

like image 160
Alex Martelli Avatar answered Nov 14 '22 01:11

Alex Martelli


This code will open the file, read the line and print it.

# Open and read file into buffer
f = open(file,"r")
lines = f.readlines()

# If we need to read line 33, and assign it to some variable
x = lines[33]
print(x)
like image 8
santosh Yadav Avatar answered Nov 14 '22 03:11

santosh Yadav


A solution that will not read more of the file than necessary is

from itertools import islice
line_number = 34

with open(filename) as f:
    # Adjust index since Python/islice indexes from 0 and the first 
    # line of a file is line 1
    line = next(islice(f, line_number - 1, line_number))

A very straightforward solution is

line_number = 34

with open(filename) as f:
    f.readlines()[line_number - 1]
like image 6
Mike Graham Avatar answered Nov 14 '22 01:11

Mike Graham


There's two ways:

  1. Read the file, line by line, stop when you've gotten to the line you want
  2. Use f.readlines() which will read the entire file into memory, and return it as a list of lines, then extract the 34th item from that list.

Solution 1

Benefit: You only keep, in memory, the specific line you want.

code:

for i in xrange(34):
    line = f.readline();
# when you get here, line will be the 34th line, or None, if there wasn't
# enough lines in the file

Solution 2

Benefit: Much less code
Downside: Reads the entire file into memory
Problem: Will crash if less than 34 elements are present in the list, needs error handling

line = f.readlines()[33]
like image 4
Lasse V. Karlsen Avatar answered Nov 14 '22 02:11

Lasse V. Karlsen