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文件

例子04: 利用fileinput将CRLF文件转为LF

import fileinput
import sys for line in fileinput.input(inplace=True):
#将Windows/DOS格式下的文本文件转为Linux的文件
if line[-2:] ==
:
line = line + sys.stdout.write(line)

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

#FileName: test.py
import sys
import fileinput for line in fileinput.input(r'C:Python27info.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-999999995718888888
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.* fileinput *.py

例子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'

Python中fileinput模块使用的更多相关文章

  1. Python中fileinput模块使用方法

    fileinput模块提供处理一个或多个文本文件的功能,可以通过使用for循环来读取一个或多个文本文件的所有行.python2.7文档关于fileinput介绍:fileinput   fileinp ...

  2. python中os模块中文帮助

    python中os模块中文帮助   python中os模块中文帮助文档文章分类:Python编程 python中os模块中文帮助文档 翻译者:butalnd 翻译于2010.1.7——2010.1.8 ...

  3. Python中optionParser模块的使用方法[转]

    本文以实例形式较为详尽的讲述了Python中optionParser模块的使用方法,对于深入学习Python有很好的借鉴价值.分享给大家供大家参考之用.具体分析如下: 一般来说,Python中有两个内 ...

  4. python中threading模块详解(一)

    python中threading模块详解(一) 来源 http://blog.chinaunix.net/uid-27571599-id-3484048.html threading提供了一个比thr ...

  5. 【转】关于python中re模块split方法的使用

    注:最近在研究文本处理,需要用到正则切割文本,所以收索到了这篇文章,很有用,谢谢原作者. 原址:http://blog.sciencenet.cn/blog-314114-775285.html 关于 ...

  6. Python中的模块介绍和使用

    在Python中有一个概念叫做模块(module),这个和C语言中的头文件以及Java中的包很类似,比如在Python中要调用sqrt函数,必须用import关键字引入math这个模块,下面就来了解一 ...

  7. python中导入模块的本质, 无法导入手写模块的解决办法

    最近身边一些朋友发生在项目当中编写自己模块,导入的时候无法导入的问题. 下面我来分享一下关于python中导入模块的一些基本知识. 1 导入模块时寻找路径 在每一个运行的python程序当中,都维护了 ...

  8. Python中time模块详解

    Python中time模块详解 在平常的代码中,我们常常需要与时间打交道.在Python中,与时间处理有关的模块就包括:time,datetime以及calendar.这篇文章,主要讲解time模块. ...

  9. Python中collections模块

    目录 Python中collections模块 Counter defaultdict OrderedDict namedtuple deque ChainMap Python中collections ...

随机推荐

  1. smtp中ehlo的使用

    以前玩smtp的时候申明都是用的helo,最近在整理邮件服务的时候,才知道还有一个叫做ehlo的(太落后了). google了一下,了解了基本上是这么个情况:ehlo是对helo的扩展,即extend ...

  2. ios7上隐藏status bar

    在iOS7上 对于设置status bar 又有了点点的改变 1.对于 UIViewController 加入了动态改变 status bar style的方法 - (UIStatusBarStyle ...

  3. Java学习笔记——MySQL的安装使用以及SQL语法简介

    在 Java 的开发中,数据库的应用是非常必要的,下面,我们为Java对于数据库的应用做一些必要的准备工作.. Java 对数据库的应用统称为 JDBC. JDBC(Java Data Base Co ...

  4. Go语言Web框架gwk介绍2

    Go语言Web框架gwk介绍 (二) HttpResult 凡是实现了HttpResult接口的对象,都可以作为gwk返回Web客户端的内容.HttpResult接口定义非常简单,只有一个方法: ty ...

  5. T-SQL编程的基本语法和思想

    通过一个很实用的例子让你学会T-SQL编程的基本语法和思想   例子需求:把Execl中的三级分类(列别的三级联动)数据导入到数据库中. Excel表中数据的显示格式: 图1 数据库中表的显示格式: ...

  6. TOGAF架构开发方法(ADM)之迁移规划阶段

    TOGAF架构开发方法(ADM)之迁移规划阶段 1.8 迁移规划(Migration Planning) 企业架构开发方法各阶段——迁移规划 1.8.1 目标 本阶段的目标是: 确保实施和迁移规划与企 ...

  7. Bek Trak Trik for wireless WPA/WPA2 & SSH & email

    FOR wireless tools: hydra, medusa, crunch, aircrack-ng packages (airodump-ng, airmon-ng, aircrack-ng ...

  8. 分享个自己做的CSDN刷下载积分软件

    对于评论里有人反映说,运行完后自动关机了,我要在这解释下,不好意思了亲们,由于昨晚开这个通宵刷积分,就加了个功能,刷完所有可刷积分后自动关机省点电.今天发布的时候忘记取消了.这里给大家带来不便请大家包 ...

  9. 关于ActiveMQ的一点总结

    ActiveMQ入门 作者:一路向北 摘要:本文主要讲述ActiveMQ的基本知识和使用方法,并简单结合spring使用ActiveMQ. 一.ActiveMQ特性和使用总览 企业消息软件从80年代起 ...

  10. ZOJ 1204 一个集合能组成多少个等式

    Additive equations Time Limit : 20000/10000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other ...