Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Reading a Particular Line from a File

Credit: Luther Blissett

Problem

You want to extract a single line from a file.

Solution

The standard linecache module makes this a snap:

import linecache
theline = linecache.getline(thefilepath, desired_line_number)

Discussion

The standard linecache module is usually the optimal Python solution for this task, particularly if you have to do this repeatedly for several of a file’s lines, as it caches the information it needs to avoid uselessly repeating work. Just remember to use the module’s clearcache function to free up the memory used for the cache, if you won’t be getting any more lines from the cache for a while but your program keeps running. You can also use checkcache if the file may have changed on disk and you require the updated version.

linecache reads and caches all of the text file whose name you pass to it, so if it’s a very large file and you need only one of its lines, linecache may be doing more work than is strictly necessary. Should this happen to be a bottleneck for your program, you may get some speed-up by coding an explicit loop, encapsulated within a function. Here’s how to do this in Python 2.2:

def getline(thefilepath, desired_line_number):
    if desired_line_number < 1: return ''
    current_line_number = 0
    for line in open(thefilepath):
        current_line_number += 1
        if current_line_number == desired_line_number: return line
    return ''

It’s not much worse in Python 2.1—you just need to change the for statement into this slightly slower ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata