pythonfileinput模块使用实例

fileinput模块可以对一个或多个文件中的内容进行迭代、遍历等操作。
该模块的input()函数有点类似文件readlines()方法,区别在于:
前者是一个迭代对象,即每次只生成一行,需要用for循环迭代。
后者是一次性读取所有行。在碰到大文件的读取时,前者无疑效率更高效。
用fileinput对文件进行循环遍历,格式化输出,查找、替换等操作,非常方便。

【典型用法】

代码如下:

import fileinput
for line in fileinput.input():
process(line)

【基本格式】

代码如下:

fileinput.input([files[, inplace[, backup[, bufsize[, mode[, openhook]]]]]])

【默认格式】

代码如下:

fileinput.input (files=none, inplace=false, backup=”, bufsize=0, mode=’r’, openhook=none)
files: #文件的路径列表,默认是stdin方式,多文件[‘1.txt’,’2.txt’,…]
inplace: #是否将标准输出的结果写回文件,默认不取代
backup: #备份文件的扩展名,只指定扩展名,如.bak。如果该文件的备份文件已存在,则会自动覆盖。
bufsize: #缓冲区大小,默认为0,如果文件很大,可以修改此参数,一般默认即可
mode: #读写模式,默认为只读
openhook: #该钩子用于控制打开的所有文件,比如说编码方式等;

【常用函数】

代码如下:

fileinput.input() #返回能够用于for循环遍历的对象
fileinput.filename() #返回当前文件的名称
fileinput.lineno() #返回当前已经读取的行的数量(或者序号)
fileinput.filelineno() #返回当前读取的行的行号
fileinput.isfirstline() #检查当前行是否是文件的第一行
fileinput.isstdin() #判断最后一行是否从stdin中读取
fileinput.close() #关闭队列

【常见例子】

例子01: 利用fileinput读取一个文件所有行

代码如下:

>>> import fileinput
>>> for line in fileinput.input(‘data.txt’):
print line,
#输出结果
python
java
c/c++
shell

命令行方式:

代码如下:

#test.py
import fileinput

for line in fileinput.input():
print fileinput.filename(),’|’,’line number:’,fileinput.lineno(),’|: ‘,line

c:>python test.py data.txt
data.txt | line number: 1 |: python
data.txt | line number: 2 |: java
data.txt | line number: 3 |: c/c++
data.txt | line number: 4 |: shell

例子02: 利用fileinput对多文件操作,并原地修改内容

代码如下:

#test.py
#—样本文件—
c:\python27>type 1.txt
first
second

c:\python27>type 2.txt
third
fourth
#—样本文件—
import fileinput

def process(line):
return line.rstrip() + ‘ line’

for line in fileinput.input([‘1.txt’,’2.txt’],inplace=1):
print process(line)

#—结果输出—
c:\python27>type 1.txt
first line
second line

c:\python27>type 2.txt
third line
fourth line
#—结果输出—

命令行方式:

代码如下:

#test.py
import fileinput

def process(line):
return line.rstrip() + ‘ line’

for line in fileinput.input(inplace = true):
print process(line)

#执行命令
c:\python27>python test.py 1.txt 2.txt

例子03: 利用fileinput实现文件内容替换,并将原文件作备份

代码如下:

#样本文件:
#data.txt
python
java
c/c++
shell

#filename: test.py
import fileinput

for line in fileinput.input(‘data.txt’,backup=’.bak’,inplace=1):
print line.rstrip().replace(‘python’,’perl’) #或者print line.replace(‘python’,’perl’),

#最后结果:
#data.txt
python
java
c/c++
shell
#并生成:
#data.txt.bak文件

代码如下:

#其效果等同于下面的方式
import fileinput
for line in fileinput.input():
print ‘tag:’,line,

#—测试结果:
d:\>python learn.py < data.txt > data_out.txt

例子04: 利用fileinput将crlf文件转为lf

代码如下:

import fileinput
import sys

for line in fileinput.input(inplace=true):
#将windows/dos格式下的文本文件转为linux的文件
if line[-2:] == “\r\n”:
line = line + “\n”
sys.stdout.write(line)

例子05: 利用fileinput对文件简单处理

代码如下:

#filename: test.py
import sys
import fileinput

for line in fileinput.input(r’c:\python27\info.txt’):
sys.stdout.write(‘=> ‘)
sys.stdout.write(line)

#输出结果
>>>
=> the zen of python, by tim peters
=>
=> beautiful is better than ugly.
=> explicit is better than implicit.
=> simple is better than complex.
=> complex is better than complicated.
=> flat is better than nested.
=> sparse is better than dense.
=> readability counts.
=> special cases aren’t special enough to break the rules.
=> although practicality beats purity.
=> errors should never pass silently.
=> unless explicitly silenced.
=> in the face of ambiguity, refuse the temptation to guess.
=> there should be one– and preferably only one –obvious way to do it.
=> although that way may not be obvious at first unless you’re dutch.
=> now is better than never.
=> although never is often better than *right* now.
=> if the implementation is hard to explain, it’s a bad idea.
=> if the implementation is easy to explain, it may be a good idea.
=> namespaces are one honking great idea — let’s do more of those!

例子06: 利用fileinput批处理文件

代码如下:

#—测试文件: test.txt test1.txt test2.txt test3.txt—
#—脚本文件: test.py—
import fileinput
import glob

for line in fileinput.input(glob.glob(“test*.txt”)):
if fileinput.isfirstline():
print ‘-‘*20, ‘reading %s…’ % fileinput.filename(), ‘-‘*20
print str(fileinput.lineno()) + ‘: ‘ + line.upper(),

#—输出结果:
>>>
——————– reading test.txt… ——————–
1: aaaaa
2: bbbbb
3: ccccc
4: ddddd
5: fffff
——————– reading test1.txt… ——————–
6: first line
7: second line
——————– reading test2.txt… ——————–
8: third line
9: fourth line
——————– reading test3.txt… ——————–
10: this is line 1
11: this is line 2
12: this is line 3
13: this is line 4

例子07: 利用fileinput及re做日志分析: 提取所有含日期的行

代码如下:

#–样本文件–
aaa
1970-01-01 13:45:30 error: **** due to system disk spacke not enough…
bbb
1970-01-02 10:20:30 error: **** due to system out of memory…
ccc

#—测试脚本—
import re
import fileinput
import sys

pattern = ‘\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}’

for line in fileinput.input(‘error.log’,backup=’.bak’,inplace=1):
if re.search(pattern,line):
sys.stdout.write(“=> “)
sys.stdout.write(line)

#—测试结果—
=> 1970-01-01 13:45:30 error: **** due to system disk spacke not enough…
=> 1970-01-02 10:20:30 error: **** due to system out of memory…

例子08: 利用fileinput及re做分析: 提取符合条件的电话号码

代码如下:

#—样本文件: phone.txt—
010-110-12345
800-333-1234
010-99999999
05718888888
021-88888888

#—测试脚本: test.py—
import re
import fileinput

pattern = ‘[010|021]-\d{8}’ #提取区号为010或021电话号码,格式:010-12345678

for line in fileinput.input(‘phone.txt’):
if re.search(pattern,line):
print ‘=’ * 50
print ‘filename:’+ fileinput.filename()+’ | line number:’+str(fileinput.lineno())+’ | ‘+line,

#—输出结果:—
>>>
==================================================
filename:phone.txt | line number:3 | 010-99999999
==================================================
filename:phone.txt | line number:5 | 021-88888888
>>>

例子09: 利用fileinput实现类似于grep的功能

代码如下:

import sys
import re
import fileinput

pattern= re.compile(sys.argv[1])
for line in fileinput.input(sys.argv[2]):
if pattern.match(line):
print fileinput.filename(), fileinput.filelineno(), line
$ ./test.py import.*re *.py
#查找所有py文件中,含import re字样的
addressbook.py 2 import re
addressbook1.py 10 import re
addressbook2.py 18 import re
test.py 238 import re

例子10: 利用fileinput做正则替换

代码如下:

#—测试样本: input.txt
* [learning python](#author:mark lutz)

#—测试脚本: test.py
import fileinput
import re

for line in fileinput.input():
line = re.sub(r’\*
(.∗)
#(.*)’, r’\1′, line.rstrip())
print(line)

#—输出结果:
c:\python27>python test.py input.txt
learning python

例子11: 利用fileinput做正则替换,不同字模块之间的替换

代码如下:

#—测试样本:test.txt
[@!$first]&[*%-second]&[third]

#—测试脚本:test.py
import re
import fileinput

regex = re.compile(r’^([^&]*)(&)([^&]*)(&)([^&]*)’)
#整行以&分割,要实现[@!$first]与[*%-second]互换
for line in fileinput.input(‘test.txt’,inplace=1,backup=’.bak’):
print regex.sub(r’\3\2\1\4\5′,line),

#—输出结果:
[*%-second]&[@!$first]&[third]

例子12: 利用fileinput根据argv命令行输入做替换

代码如下:

#—样本数据: host.txt
# localhost is used to configure the loopback interface
# when the system is booting. do not change this entry.
127.0.0.1 localhost
192.168.100.2 www.test2.com
192.168.100.3 www.test3.com
192.168.100.4 www.test4.com

#—测试脚本: test.py
import sys
import fileinput

source = sys.argv[1]
target = sys.argv[2]
files = sys.argv[3:]

for line in fileinput.input(files,backup=’.bak’,openhook=fileinput.hook_encoded(“gb2312”)):
#对打开的文件执行中文字符集编码
line = line.rstrip().replace(source,target)
print line

#—输出结果:
c:\>python test.py 192.168.100 127.0.0 host.txt
#将host文件中,所有192.168.100转换为:127.0.0
127.0.0.1 localhost
127.0.0.2 www.test2.com
127.0.0.3 www.test3.com
127.0.0.4 www.test4.com

Posted in 未分类

发表评论