This article mainly introduces the Python fileinput module uses the example, the Fileinput module may traverse the text file all lines, this article gives its use code example, needs the friend to be possible to refer to under
The Fileinput module can traverse all lines of a text file. It works like ReadLines, except that it does not read all the rows to the list but creates a Xreadlines object.
The following are common functions in the Fileinput module
Input () #它会返回能够用于for循环遍历的对象.
FileName () #返回当前文件的名称
Lineno () #返回当前 (cumulative) Number of rows
Filelineno () #返回当前文件的行数
Isfirstline () #检查当前行是否是文件的第一行
The 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
"" To process multiple text files and to transport the travel number ""
For line in Fileinput.input (Glob.glob ("*.sh")):
If Fileinput.isfirstline ():
Print "------reading%s------N"% fileinput.filename ()
Print str (Fileinput.lineno ()) + "" + Line
Example:
The 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]#