Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources]

David Ascher, Alex Martelli, Anna Ravenscroft

نسخه متنی -صفحه : 394/ 48
نمايش فراداده

Recipe 2.4. Reading a Specific Line from a File

Credit: Luther Blissett

Problem

You want to read from a text file a single line, given the line number.

Solution

The standard Python library linecache module makes this task 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. linecache is particularly useful when you have to perform this task repeatedly for several lines in a file, since linecache caches information to avoid uselessly repeating work. When you know that you won't be needing any more lines from the cache for a while, call the module's clearcache function to free the memory used for the cache. You can also use checkcache if the file may have changed on disk and you must make sure you are getting 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 an increase in speed by coding an explicit loop, encapsulated within a function, such as:

def getline(thefilepath, desired_line_number):
if desired_line_number < 1: return ''
for current_line_number, line in enumerate(open(thefilepath, 'rU')):
if current_line_number == desired_line_number-1: return line
return ''

The only detail requiring attention is that enumerate counts from 0, so, since we assume the desired_line_number argument counts from 1, we need the -1 in the == comparison.

See Also

Documentation for the linecache module in the Library Reference and Python in a Nutshell; Perl Cookbook recipe 8.8.