Python 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-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'
复制代码

 

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


转自:http://www.jb51.net/article/67167.htm

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
本课程详细讲解了以下内容:    1.jsp环境搭建及入门、虚拟路径和虚拟主机、JSP执行流程    2.使用Eclipse快速开发JSP、编码问题、JSP页面元素以及request对象、使用request对象实现注册示例    3.请求方式的编码问题、response、请求转发和重定向、cookie、session执行机制、session共享问题     4.session与cookie问题及application、cookie补充说明及四种范围对象作用域     5.JDBC原理及使用Statement访问数据库、使用JDBC切换数据库以及PreparedStatement的使用、Statement与PreparedStatement的区别     6.JDBC调用存储过程和存储函数、JDBC处理大文本CLOB及二进制BLOB类型数据     7.JSP访问数据库、JavaBean(封装数据和封装业务逻辑)     8.MVC模式与Servlet执行流程、Servlet25与Servlet30的使用、ServletAPI详解与源码分析     9.MVC案例、三层架构详解、乱码问题以及三层代码流程解析、完善Service和Dao、完善View、优化用户体验、优化三层(加入接口和DBUtil)    1 0.Web调试及bug修复、分页SQL(Oracle、MySQL、SQLSERVER)     11.分页业务逻辑层和数据访问层Service、Dao、分页表示层Jsp、Servlet     12.文件上传及注意问题、控制文件上传类型和大小、下载、各浏览器下载乱码问题     13.EL表达式语法、点操作符和中括号操作符、EL运算、隐式对象、JSTL基础及set、out、remove     14.过滤器、过滤器通配符、过滤器链、监听器     15.session绑定解绑、钝化活化     16.以及Ajax的各种应用     17. Idea环境下的Java Web开发
可以参考以下代码实现一个基本的 Bootstrap Fileinput: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Bootstrap Fileinput Example</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.1.2/css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" /> </head> <body> <div class="container mt-5"> <form action="#" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="inputFile">Choose file</label> <input id="inputFile" name="inputFile" type="file" class="file"> </div> </form> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.1.2/js/plugins/piexif.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.1.2/js/fileinput.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.1.2/themes/fa/theme.min.js"></script> <script> $(document).ready(function() { $("#inputFile").fileinput({ theme: 'fa', showUpload: false, allowedFileExtensions: ['jpg', 'jpeg', 'png', 'gif'] }); }); </script> </body> </html> ``` 在上述代码中,我们引入了 Bootstrap、jQuery 和 Bootstrap Fileinput 的 CSS 和 JS 文件,并在页面中创建了一个表单和一个文件选择器。在加载完页面后,我们使用 jQuery 的 fileinput 插件对文件选择器进行初始化,并设置了一些参数,如主题、是否显示上传按钮和允许上传的文件类型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值