Auxiliary Modules for File I/O

File objects supply all the minimal indispensable functionality needed for file I/O. Some auxiliary Python library modules, however, offer convenient supplementary functionality, making I/O even easier and handier in several important cases.

The fileinput Module

The fileinput module lets you loop over all the lines in a list of text files. Performance is good, comparable to the performance of direct iteration on each file, since fileinput uses buffering to minimize I/O. You can therefore use module fileinput for line-oriented file input whenever you find the module’s rich functionality convenient, with no worries about performance. The input function is the key function of module fileinput, and the module also provides a FileInput class whose methods support the same functionality as the module’s functions.

close

close( )

Closes the whole sequence so that iteration stops and no file remains open.

FileInput

class FileInput(files=None, inplace=False, backup='', bufsize=0)

Creates and returns an instance f of class FileInput. Arguments are the same as for fileinput.input, and methods of f have the same names, arguments, and semantics as functions of module fileinput. f also supplies a method readline, which reads and returns the next line. You can use class FileInput explicitly when you want to nest or mix loops that read lines from more than one sequence of files.

filelineno

filelineno( )

Returns the number of lines read so far from the file now being read. ...

Get Python in a Nutshell, 2nd Edition 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.