Auxiliary Modules for File I/O
File objects supply all functionality that is strictly needed for file I/O. There are some auxiliary Python library modules, however, that offer convenient supplementary functionality, making I/O even easier and handier in several important special cases.
The fileinput Module
The fileinput
module
lets you loop over all the lines in a list of text files. Performance
is quite good, comparable to the performance of direct iteration on
each file, since fileinput
uses internal buffering
to minimize I/O. Therefore, you can use module
fileinput
for line-oriented file input whenever
you find the module’s rich functionality convenient,
without worrying about performance. The input
function is the main function of module fileinput
,
and the module also provides a FileInput
class
that supports the same functionality as the module’s
functions.
The linecache Module
The
linecache
module lets you read a given line
(specified by number) from a file with a given name. The module keeps
an internal cache, so if you need to read several lines from a file,
the operation is cheaper than opening and examining the file each
time. Module linecache
exposes the following
functions.
The struct Module
The
struct
module lets you pack binary data into a
string, and then unpack the bytes of such a string back into the data
they represent. Such operations can be useful for various kinds of
low-level programming. Most often, you use module
struct
to interpret data records from binary ...
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.