50

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

Teun Zengerink
  • 4,277
  • 5
  • 30
  • 32
ArchHaskeller
  • 1,270
  • 1
  • 12
  • 28
  • 2
    http://stackoverflow.com/questions/2081836/reading-specific-lines-only-python – Alok Singhal Mar 15 '10 at 01:18
  • 1
    Note that if you follow one of the many solutions that opens your file, you want to do this with a `with` block (or `try`/`finally` in pre-2.5) to ensure your file gets closed. Many of the solutions have the potential to raise exceptions, for example if your file is unexpectedly shorter than 34 lines. – Mike Graham Mar 15 '10 at 02:41
  • http://stackoverflow.com/questions/620367/python-how-to-jump-to-a-particular-line-in-a-huge-text-file python: how to jump to a particular line in a huge text file? – jfs Mar 15 '10 at 05:38

8 Answers8

104

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!

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 5
    +1 for a nice elegant solution and we (or at least I) learned something new. – Justin Ethier Mar 15 '10 at 01:28
  • nice, but if other processing is needed on other lines, opening the file is still needed. – ghostdog74 Mar 15 '10 at 02:32
  • 1
    @ghostdog, if the "processing" is on specifically numbered lines, just keep using `linecache` -- as the name implies, it caches things for you. A weird mix where some lines are accessed as numbered and others need looping on can be handled in different ways, but such weird mixes are hardly a common use case. – Alex Martelli Mar 15 '10 at 02:58
  • +1 you are a genius Alex. I learn at least `2` new things from you everyday :D – Pratik Deoghare Mar 15 '10 at 03:02
  • @MachineCharmer, heh, flattery will get you anywhere;-). – Alex Martelli Mar 15 '10 at 03:25
  • @alex, what i actually mean is, beside processing those specific line numbers, OP may want to use the other lines as well, maybe to output to some files etc etc..... Of course, this is not in OP's question, but just a thought. – ghostdog74 Mar 15 '10 at 03:47
8

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)
Gustav Bertram
  • 14,591
  • 3
  • 40
  • 65
santosh Yadav
  • 81
  • 1
  • 1
6

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]
IAbstract
  • 19,551
  • 15
  • 98
  • 146
Mike Graham
  • 73,987
  • 14
  • 101
  • 130
4

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]
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
2

You could just read all the lines and index the line your after.

line = open('filename').readlines()[33]
tarn
  • 2,192
  • 2
  • 13
  • 17
1
for linenum,line in enumerate(open("file")):
    if linenum+1==34: print line.rstrip()
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • don't understand. what many lines? if OP wants to stop at line 34, just do a break. Its still better than reading the whole file into memory. – ghostdog74 Mar 15 '10 at 03:44
1

I made a thread about this and didn't receive help so I took matter into my own hands.

Not any complicated code here.

import linecache
#Simply just importing the linecache function to read our line of choosing

number = int(input("Enter a number from 1-10 for a random quote "))
#Asks the user for which number they would like to read(not necessary) 

lines = linecache.getline("Quotes.txt", number)
#Create a new variable in order to grab the specific line, the variable 
#integer can be replaced by any integer of your choosing.

print(lines)
#This will print the line of your choosing.

If you are completing this in python make sure you have both files (.py) and (.txt) in the same location otherwise python will not be able to retrieve this, unless you specify the file location. EG.

linecache.getline("C:/Directory/Folder/Quotes.txt

This is used when the file is in another folder than the .py file you are using.

Hope this helps!

EgMusic
  • 136
  • 17
Awais
  • 55
  • 7
0

Option that always closes the file and doesn't load the whole file into memory

with open('file.txt') as f:
    for i, line in enumerate(f):
        if i+1 == 34: break
    print(line.rstrip())
Benjamin Ziepert
  • 1,345
  • 1
  • 15
  • 19