fileinput模块 分类: python基础学习 python 小练习 python Module 2013-08-15 17:18 417人阅读 评论(0) 收藏
fileinput.input (files=None, inplace=False, backup='', bufsize=0, mode='r', openhook=None)
参数
files :文件的路径列表
inplace:是否将标准输出(print方法)的结果写回文件
backup : 备份文件的扩展名,只指定扩展名,如.bak。如果该文件的备份文件已存在,则会自动覆盖。
bufsize :缓冲区大小
mode :读写模式
参数inplace如果设为1,那么就将读到的行,输出到输入文件中。如果有backup这个参数,就会将源文件内容输入到备份文件中,输出还会输出到输入文件中。
#coding:utf-8 ''' 1. fileinput.isfirstline() 判断是否是新文件的开始 2. fileinput.filename() 输出文件名称 3. fileinput.filelineno() 输出当前行在所在文件中的行数 4. fileinput.lineno() 输出当前已经输出的总行数 5. fileinput.nextfile() 跳出当前遍历的文件,跳至下个文件 ''' import fileinput def main(): for line in fileinput.input([r"G:\\rr.txt",r"G:\\rr2.txt"]): #判断是否是新文件的开始,如果是,则输出文件名称 if fileinput.isfirstline(): print '\n'+'*'*10 print fileinput.filename() #输出行号、行内容 print fileinput.filelineno(),line, #跳至下个文件 if line.strip() =="lll": fileinput.nextfile() #输出当前已经输出的总行数 print fileinput.lineno(),line, if __name__ == '__main__': main()
[例]
==================================
G盘有test.txt文件,内容如下:
I am a test file
want to sing a song for you
do you want to listen?
listen.....
listen.....
listen.....
I heard, that your settled down.
That you, found a girl and your married now.
I heard that your dreams came true.
Guess she gave you things, I didn't give to you.
Old friend, why are you so shy?
I hate to turn up out of the blue uninvited.
--------------------------------------------------------------
程序代码如下:
import fileinput
for line in fileinput.input(r'G:\\test.txt',inplace = True,backup ='.bak'):
print '%-60s # %2i' %(line, fileinput.lineno())
--------------------------------------------------------------
执行程序后,text.txt内容如下:
I am a test file # 1
want to sing a song for you # 2
do you want to listen? # 3
listen..... # 4
listen..... # 5
listen..... # 6
I heard, that your settled down. # 7
That you, found a girl and your married now. # 8
I heard that your dreams came true. # 9
Guess she gave you things, I didn't give to you. # 10
Old friend, why are you so shy? # 11
I hate to turn up out of the blue uninvited. # 12
--------------------------------------------------------------------
且在G盘下生产了test.txt.bak文件,内容与执行程序前的test.txt内容一致。