Python fileinput module instance, pythonfileinput
The fileinput module can traverse all rows of a text file. It works in a similar way as readlines. The difference is that it creates an xreadlines object instead of reading all rows into the list.
The following are common functions in the fileinput module:
Input () # It returns objects that can be used for loop traversal.
Filename () # returns the name of the current file.
Lineno () # returns the current (accumulative) number of rows
Filelineno () # returns the number of rows of the current file.
Isfirstline () # Check whether the current row is the first line of the file
Copy codeThe Code is as follows:
#! /Bin/env python
# Coding = UTF-8
Import fileinput
Import sys
Import glob
Import string
'''Process a text file '''
For line in fileinput. input ("tab. sh "):
Print line
'''Process multiple text files and output the row number '''
For line in fileinput. input (glob. glob ("*. sh ")):
If fileinput. isfirstline ():
Print "------ reading % s ------ \ n" % fileinput. filename ()
Print str (fileinput. lineno () + "" + line
Example:
Copy codeThe Code is as follows:
[Root @ rac1 admin] # python ftest. py
Abc_permission_collection
Abc_user
Abc_user_group_relationship
------ Reading c. sh ------
1 c
2 cc
3 ccc
------ Reading tab. sh ------
4 abc_permission_collection
5 abc_user
6 abc_user_group_relationship
[Root @ rac1 admin] #