1. Home
  2. Computing & Technology
  3. Python

Reading a Single Line from a File With Python
Using the linecache Module

From , former About.com Guide

If you ever find that you need to read the same line from a file every time you read it, Python makes this task a three-line program. First, import the linecache module:

import linecache

The linecache module allows you to access any line from any file. Of its three methods, the one you are likely to use the most is getline. The syntax for getline is as follows:

linecache.getline('filename', line_number)

If you have a file called 'myfile.txt' and would like to read line 138 from it, getline allows you to do so with ease.

retrieved_line = linecache.getline('myfile.txt', 138)

Then you can simply print retrieved_line or otherwise manipulate the data of line 138 without doing surgery on the file itself.

If you would like to read more about the linecache module, visit the Python documentation .

More Python Quick Tips
Explore Python
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Python
  4. ScripTips
  5. Reading a Single Line from a File With Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.