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-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.* 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'

', line.rstrip()) print(line) #---输出结果: c:Python27>python test.py input.txt

Learning Python

python fileinput模块next_Python中fileinput模块介绍相关推荐

  1. python fileinput模块next_Python中的fileinput模块的简单实用示例

    这几天有这样一个需求,要将用户登陆系统的信息统计出来,做成一个报表.当用户登陆成功的时候,服务器会往日志文件里写一条像下面这种格式的记录:"日期时间@用户名@IP",这样的日志文件 ...

  2. python shelve模块_Python中shelve模块的简单介绍(附示例)

    本篇文章给大家带来的内容是关于Python中shelve模块的简单介绍(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. shelve:对象持久化的保存的模块,将对象保存到文件 ...

  3. python xlrd课程_python中xlrd模块的使用详解

    一.xlrd的安装 打开cmd输入pip install xlrd安装完成即可 二.xlrd模块的使用 下面以这个工作簿为例 1.导入模块 import xlrd 2.打开工作薄 # filename ...

  4. python中产生随机数模块_Python中random模块生成随机数详解

    Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...

  5. 简述python中怎样导入模块_Python中导入模块的两种模式,import

    import import pandas import pandas as pd 使用函数方式:.(),或者.() 比如 pandas.read_csv("data/stock.csv&qu ...

  6. python中自带的模块_python中的模块详解

    概念 python中的模块是什么?简而言之,在python中,一个文件(以".py"为后缀名的文件)就叫做一个模块,每一个模块在python里都被看做是一个独立的文件.模块可以被项 ...

  7. python中mysqldb模块_python中MySQLdb模块用法实例

    本文实例讲述了python中MySQLdb模块用法.分享给大家供大家参考.具体用法分析如下: MySQLdb其实有点像php或asp中连接数据库的一个模式了,只是MySQLdb是针对mysql连接了接 ...

  8. python pygame模块_python中pygame模块用法实例

    本文实例讲述了python中pygame模块用法,分享给大家供大家参考.具体方法如下: import pygame, sys from pygame.locals import * #set up p ...

  9. python从包中导入模块_Python中包,模块导入的方法

    Python中包,模块导入的方法 http://www.cnblogs.com/allenblogs/archive/2011/05/24/2055149.html 1. import modname ...

最新文章

  1. ElasticSearch 面试 4 连问,你顶得住么?
  2. 第1章 编程心理门槛
  3. sql字符串函数_另一堆SQL字符串函数
  4. scipy.sparse、pandas.sparse、sklearn稀疏矩阵的使用
  5. 人和人之间不要靠的太近
  6. 路由器与交换机组网性能的综合对比分析
  7. GDI GDI+ 的区别
  8. toolchain安装教程支持_网上现成toolchain安装操作
  9. fx5800p编程教程_fx5800P编程计算器操作方法.pdf
  10. win7计算机设置成不黑屏,教你win7开机黑屏
  11. 使用 className 修改样式属性
  12. 从双曲几何到Gauss-Bonnet-Chern定理
  13. Strusts框架学习(一)
  14. 运动模糊 motion blur
  15. 【Android】音乐播放器APP的设计与实现
  16. nginx、php本地配置https
  17. 蓝桥杯c语言校内选拔赛试题,2013年蓝桥杯校内选拔赛C语言B组.docx
  18. 万字好文!Docker环境部署Prometheus+Grafana监控系统
  19. uni-app移动端开发技巧总结
  20. 要给视频批量添加背景音乐该怎么办?

热门文章

  1. 【THINKPAD X240Intel Management Engine9.5升级10.0失败解决方案】
  2. Camtasia Studio2023Mac最新电脑版屏幕录像软件
  3. js 写斐波那契数列
  4. 《软件框架设计的艺术》试读:1.2 软件的演变过程
  5. C++线程池QueueUserWorkItem
  6. Catia圆柱凸轮设计
  7. 表白神器,适合表白的神器
  8. luogu1966 火柴排队
  9. 高并发系统设计——分布式锁解决方案
  10. 记实验室服务器网安事件始末