Pyhton 学习总结 21 :fileinput模块
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
Pyhton 学习总结 21 :fileinput模块的更多相关文章
- day23 Pyhton学习 昨日回顾.re模块.序列化模块
一.昨日回顾 #__file__查看当前文件所在的绝对路径 #time 时间模块 time.time 获取当前时间戳时间 字符串->time.strptime->结构化->mktim ...
- Python3学习笔记(urllib模块的使用)转http://www.cnblogs.com/Lands-ljk/p/5447127.html
Python3学习笔记(urllib模块的使用) 1.基本方法 urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, ...
- python标准库介绍——15 fileinput 模块详解
``fileinput`` 模块允许你循环一个或多个文本文件的内容, 如 [Example 2-1 #eg-2-1] 所示. ====Example 2-1. 使用 fileinput 模块循环一个文 ...
- Python Fileinput 模块介绍
作者博文地址:http://www.cnblogs.com/spiritman/ fileinput模块提供处理一个或多个文本文件的功能,可以通过使用for循环来读取一个或多个文本文件的所有行. [默 ...
- Python Fileinput 模块
作者博文地址:http://www.cnblogs.com/liu-shuai/ fileinput模块提供处理一个或多个文本文件的功能,可以通过使用for循环来读取一个或多个文本文件的所有行. [默 ...
- fileinput模块
刚才练习的时候,报如下错误: AttributeError: module 'fileinput' has no attribute 'input',后来Google参考这篇文章https://mai ...
- Python基础【第十一篇】文件操作(file()、open()方法和fileinput模块)
一.file/open 内置函数 file函数的方法: 注:file 和 open的用法和功能相同这里只对file进行分析 file(‘filename’,’mode’) file(‘filename ...
- Ext.Net学习笔记21:Ext.Net FormPanel 字段验证(validation)
Ext.Net学习笔记21:Ext.Net FormPanel 字段验证(validation) 作为表单,字段验证当然是不能少的,今天我们来一起看看Ext.Net FormPanel的字段验证功能. ...
- Python中fileinput模块使用
fileinput模块可以对一个或多个文件中的内容进行迭代.遍历等操作.该模块的input()函数有点类似文件 readlines()方法,区别在于前者是一个迭代对象,需要用for循环迭代,后者是一次 ...
随机推荐
- Spring MVC过滤器-字符集过滤器(CharacterEncodingFilter)
spring的字符集过滤通过用于处理项目中的乱码问题,该过滤器位于org.springframework.web.filter包中,指向类CharacterEncodingFilter,Charact ...
- Mockito学习资料
官网:http://mockito.org/ https://dzone.com/refcardz/mockito
- 让你的APP支持iPhone5
让你的APP支持iPhone5 前言 国庆节前,为了支持 iPhone5 的屏幕分辨率 (640 象素 x 1136 象素),我尝试着升级粉笔网 iPhone 客户端.整个过程花了大概一天的时间,我把 ...
- .net 新闻点击量修改,避免恶意刷新
DataTable dt = bll.GetNewsByID(id);//根据ID获取的新闻详细内容 if (dt != null && dt.Rows.Count > 0) { ...
- php引用&符号详解——————给变量起小名
学习了这篇博客[http://blog.csdn.net/jiedushi/article/details/6428585] php中引用采用的是“写时拷贝”的原理,就是除非发生写操作,指向同一个地址 ...
- 微信APP支付Java后端回调处理
package com.gaoxiao.framework.controller.gaojia; import com.gaoxiao.framework.commonfiles.entity.Sta ...
- zju(8)串口通信实验
1.实验目的 1.学习和掌握linux下串口的操作方法以及应用程序的编写: 二.实验内容 1.编写EduKit-IV实验箱Linux操作系统下串口的应用程序,运行时只需要将串口线的一端连接到开发板的c ...
- HDU1004之总是wa的细节问题
#include <stdio.h> #include <string.h> int main() { ][]; int n, i, k, j, max, max_i; ){ ...
- Unity学习疑问记录之时间变量
1.Time.deltaTime 以秒计算,完成最后一帧的时间 放在Update()函数中的代码是以帧来执行的.如果我们需要物体的移动以秒来执行.我们需要将物体移动的值乘以Time.deltaTime ...
- IOS第18天(7,CAKeyframeAnimation-图标抖动)
*** #import "HMViewController.h" #define angle2radian(x) ((x) / 180.0 * M_PI) @interface H ...