Python fileinput模塊使用實(shí)例
fileinput模塊可以對(duì)一個(gè)或多個(gè)文件中的內(nèi)容進(jìn)行迭代、遍歷等操作。
該模塊的input()函數(shù)有點(diǎn)類似文件readlines()方法,區(qū)別在于:
前者是一個(gè)迭代對(duì)象,即每次只生成一行,需要用for循環(huán)迭代。
后者是一次性讀取所有行。在碰到大文件的讀取時(shí),前者無疑效率更高效。
用fileinput對(duì)文件進(jìn)行循環(huán)遍歷,格式化輸出,查找、替換等操作,非常方便。
【典型用法】
import fileinput
for line in fileinput.input():
process(line)
【基本格式】
fileinput.input([files[, inplace[, backup[, bufsize[, mode[, openhook]]]]]])
【默認(rèn)格式】
fileinput.input (files=None, inplace=False, backup='', bufsize=0, mode='r', openhook=None)
files: #文件的路徑列表,默認(rèn)是stdin方式,多文件['1.txt','2.txt',...]
inplace: #是否將標(biāo)準(zhǔn)輸出的結(jié)果寫回文件,默認(rèn)不取代
backup: #備份文件的擴(kuò)展名,只指定擴(kuò)展名,如.bak。如果該文件的備份文件已存在,則會(huì)自動(dòng)覆蓋。
bufsize: #緩沖區(qū)大小,默認(rèn)為0,如果文件很大,可以修改此參數(shù),一般默認(rèn)即可
mode: #讀寫模式,默認(rèn)為只讀
openhook: #該鉤子用于控制打開的所有文件,比如說編碼方式等;
【常用函數(shù)】
fileinput.input() #返回能夠用于for循環(huán)遍歷的對(duì)象
fileinput.filename() #返回當(dāng)前文件的名稱
fileinput.lineno() #返回當(dāng)前已經(jīng)讀取的行的數(shù)量(或者序號(hào))
fileinput.filelineno() #返回當(dāng)前讀取的行的行號(hào)
fileinput.isfirstline() #檢查當(dāng)前行是否是文件的第一行
fileinput.isstdin() #判斷最后一行是否從stdin中讀取
fileinput.close() #關(guān)閉隊(duì)列
【常見例子】
例子01: 利用fileinput讀取一個(gè)文件所有行
>>> import fileinput
>>> for line in fileinput.input('data.txt'):
print line,
#輸出結(jié)果
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對(duì)多文件操作,并原地修改內(nèi)容
#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)
#---結(jié)果輸出---
c:\Python27>type 1.txt
first line
second line
c:\Python27>type 2.txt
third line
fourth line
#---結(jié)果輸出---
命令行方式:
#test.py
import fileinput
def process(line):
return line.rstrip() + ' line'
for line in fileinput.input(inplace = True):
print process(line)
#執(zhí)行命令
c:\Python27>python test.py 1.txt 2.txt
例子03: 利用fileinput實(shí)現(xiàn)文件內(nèi)容替換,并將原文件作備份
#樣本文件:
#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'),
#最后結(jié)果:
#data.txt
Python
Java
C/C++
Shell
#并生成:
#data.txt.bak文件
#其效果等同于下面的方式
import fileinput
for line in fileinput.input():
print 'Tag:',line,
#---測試結(jié)果:
d:\>python Learn.py < data.txt > data_out.txt
例子04: 利用fileinput將CRLF文件轉(zhuǎn)為LF
import fileinput
import sys
for line in fileinput.input(inplace=True):
#將Windows/DOS格式下的文本文件轉(zhuǎn)為Linux的文件
if line[-2:] == "\r\n":
line = line + "\n"
sys.stdout.write(line)
例子05: 利用fileinput對(duì)文件簡單處理
#FileName: test.py
import sys
import fileinput
for line in fileinput.input(r'C:\Python27\info.txt'):
sys.stdout.write('=> ')
sys.stdout.write(line)
#輸出結(jié)果
>>>
=> 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(),
#---輸出結(jié)果:
>>>
-------------------- 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)
#---測試結(jié)果---
=> 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做分析: 提取符合條件的電話號(hào)碼
#---樣本文件: phone.txt---
010-110-12345
800-333-1234
010-99999999
05718888888
021-88888888
#---測試腳本: test.py---
import re
import fileinput
pattern = '[010|021]-\d{8}' #提取區(qū)號(hào)為010或021電話號(hào)碼,格式: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,
#---輸出結(jié)果:---
>>>
==================================================
Filename:phone.txt | Line Number:3 | 010-99999999
==================================================
Filename:phone.txt | Line Number:5 | 021-88888888
>>>
例子09: 利用fileinput實(shí)現(xiàn)類似于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'<h2 id="\2">\1</h2>', line.rstrip())
print(line)
#---輸出結(jié)果:
c:\Python27>python test.py input.txt
<h2 id="author:Mark Lutz">Learning Python</h2>
例子11: 利用fileinput做正則替換,不同字模塊之間的替換
#---測試樣本:test.txt
[@!$First]&[*%-Second]&[Third]
#---測試腳本:test.py
import re
import fileinput
regex = re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')
#整行以&分割,要實(shí)現(xiàn)[@!$First]與[*%-Second]互換
for line in fileinput.input('test.txt',inplace=1,backup='.bak'):
print regex.sub(r'\3\2\1\4\5',line),
#---輸出結(jié)果:
[*%-Second]&[@!$First]&[Third]
例子12: 利用fileinput根據(jù)argv命令行輸入做替換
#---樣本數(shù)據(jù): 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")):
#對(duì)打開的文件執(zhí)行中文字符集編碼
line = line.rstrip().replace(source,target)
print line
#---輸出結(jié)果:
c:\>python test.py 192.168.100 127.0.0 host.txt
#將host文件中,所有192.168.100轉(zhuǎn)換為: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
相關(guān)文章
聊聊基于pytorch實(shí)現(xiàn)Resnet對(duì)本地?cái)?shù)據(jù)集的訓(xùn)練問題
本文項(xiàng)目是使用Resnet模型來識(shí)別螞蟻和蜜蜂,其一共有三百九十六張的數(shù)據(jù),訓(xùn)練集只有兩百多張(數(shù)據(jù)集很小),運(yùn)行十輪后,分別對(duì)訓(xùn)練集和測試集在每一輪的準(zhǔn)確率,對(duì)pytorch實(shí)現(xiàn)Resnet本地?cái)?shù)據(jù)集的訓(xùn)練感興趣的朋友一起看看吧2022-03-03python文件讀寫操作與linux shell變量命令交互執(zhí)行的方法
這篇文章主要介紹了python文件讀寫操作與linux shell變量命令交互執(zhí)行的方法,涉及對(duì)文件操作及Linux shell交互的技巧,需要的朋友可以參考下2015-01-01淺談keras中的后端backend及其相關(guān)函數(shù)(K.prod,K.cast)
這篇文章主要介紹了淺談keras中的后端backend及其相關(guān)函數(shù)(K.prod,K.cast),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06python遠(yuǎn)程調(diào)用rpc模塊xmlrpclib的方法
今天小編就為大家分享一篇python遠(yuǎn)程調(diào)用rpc模塊xmlrpclib的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01Pyqt5 實(shí)現(xiàn)窗口縮放,控件在窗口內(nèi)自動(dòng)伸縮的操作
這篇文章主要介紹了Pyqt5 實(shí)現(xiàn)窗口縮放,控件在窗口內(nèi)自動(dòng)伸縮的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03Python 3.x 安裝opencv+opencv_contrib的操作方法
下面小編就為大家分享一篇Python 3.x 安裝opencv+opencv_contrib的操作方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04使用Python對(duì)微信好友進(jìn)行數(shù)據(jù)分析
這篇文章主要介紹了使用Python對(duì)微信好友進(jìn)行數(shù)據(jù)分析的實(shí)現(xiàn)代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-06-06