321gf 发表于 2016-6-22 09:30:13

python模块fileinput

    在python脚本语言中的fileinput模块可以对一个或多个文件的内容进行迭代,编历操作.常用的函数:
   fileinput.input()          #读取文件的内容
   fileinput.filename()    #文件的名称
   fileinput.lineno()      #当前读取行的数量
   fileinput.filelineno()   #读取行的行号

   fileinput.isfirstline()   #当前行是否是文件第一行

   fileinput.isstdin()       #判断最后一行是否从stdin中读取
   fileinput.close()         #关闭队列


1.加载fileinput模块和使用input属性

格式:
input(files=None, inplace=0, backup='', bufsize=0, mode='r', openhook=None)
files:文件的路径列表,默认是stdin方式,多文件['1.txt','2.txt']写成列表
inplace:是否将标准输出的结果写回文件
backup:备份文件的扩展名,只定义扩展名
bufsize:缓冲区的大小,默认是0
mode:读写模式,默认为只读
openhook:控制打开的文件

2.备份文件内容
# vim 1.py

#!/bin/env python
#! _*_ coding:utf8 _*
import fileinput

for line in fileinput.input('qwe.py','/root/1.txt','.back'):   #.back是备份后文件的后缀
    print line,      #后面逗号表示不换行
# python 1.pyqwe.py
# ll qwe.py*
-rwxr-xr-x 1 root root 315 Jun 21 18:10 qwe.py
-rwxr-xr-x 1 root root 315 Jun 21 18:07 qwe.py.back
#


3.格式化输出
# vim 1.py
#!/bin/env python
#! _*_ coding:utf8 _*
import fileinput

for i in fileinput.input():
    print fileinput.filename(),'|','Line Number:','|',fileinput.lineno(),'|:',i.lstrip(),
# python 1.pyqwe.py
qwe.py | Line Number: | 1 |: #!/bin/env python
qwe.py | Line Number: | 2 |: #!-*- coding:UTF-8 -*-
qwe.py | Line Number: | 3 |:qwe.py | Line Number: | 4 |: def lines(file):
qwe.py | Line Number: | 5 |: for line for file:
qwe.py | Line Number: | 6 |: yield line
qwe.py | Line Number: | 7 |: yield '\n'
qwe.py | Line Number: | 8 |:qwe.py | Line Number: | 9 |: def blocks(file):
qwe.py | Line Number: | 10 |: blosk=[]
qwe.py | Line Number: | 11 |: for line in lines(file):
qwe.py | Line Number: | 12 |: if line.strip():
qwe.py | Line Number: | 13 |: block.append(line)
qwe.py | Line Number: | 14 |: elif block:
qwe.py | Line Number: | 15 |: yield ''.join(block).strip()
qwe.py | Line Number: | 16 |: block=[]

4.修改文件内容
# vim 1.py
def process(line):
    return line.rstrip()+'   line'

for line in fileinput.input(['1.txt','2.txt'],inplace=1):
    print process(line)
# python 1.py 1.txt
# cat 1.txt
1111   line
2222   line
3333   line
4444   line
# cat 2.txt
777   line
888   line
999   line
#


5.查找文件中的内容
# vim 1.py
#!/bin/env python
#! _*_ coding:utf8 _*
import fileinput
import sys
import re


a='d{2}:d{2}:d{2}'
for i in fileinput.input('/var/log/yum.log',backup='.back',inplace=1):
    if re.search(a,i):
      sys.stdout.write(line)
# python 1.py
# ll /var/log/yum.log*
-rw-------1 root root   0 Jun 21 18:36 /var/log/yum.log
-rw-------1 root root   640 Jun3 11:39 /var/log/yum.log.back
#

页: [1]
查看完整版本: python模块fileinput