Reading a Single Line from a File


print linecache.getline(filePath, 1) print linecache.getline(filePath, 3) linecache.clearcache()

The linecache module in Python is an extremely useful tool if you need to access specific lines in certain files multiple times. The linecache module caches the lines in a file in memory the first time they are read. Although this does not provide any advantage the first time the file is accessed, it does speed up consecutive accesses immensely.

The getline(filename, lineno) function of the linecache module accepts a filename and line number as its arguments. It then reads the line from the file, caches it in memory for later use, and then returns a string representation of the line. The clearcache() function of the linecache module frees up the cache memory by removing all lines that have been previously read.

import linecache filePath = "input.txt" print linecache.getline(filePath, 1) print linecache.getline(filePath, 3) linecache.clearcache()


line_cache.py

Line 1 Line 3


Output from line_cache.py code



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net