Python

  1. Home
  2. Computing & Technology
  3. Python

Reading a Single Line from a File With Python

Using the linecache Module

From Al Lukaszewski, for About.com

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

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

Python

  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.