Python fileinput模块使用介绍

WBOY
Release: 2016-06-10 15:18:37
Original
1598 people have browsed it

fileinput模块提供处理一个或多个文本文件的功能,可以通过使用for循环来读取一个或多个文本文件的所有行。它的工作方式和readlines很类似,不同点在于它不是将全部的行读到列表中而是创建了一个xreadlines对象。

下面是fileinput模块中的常用函数:

input()    #返回能够用于for循环遍历的对象
filename()  #返回当前文件的名称
lineno()   #返回当前已经读取的行的数量(或者序号)
filelineno() #返回当前读取的行的行号
isfirstline() #检查当前行是否是文件的第一行
Copy after login

创建测试文件test.txt:

# cat > test.txt << EOF
Hello,<span class="wp_keywordlink">Python</span>
www.jb51.net
This is a test file
EOF
Copy after login

利用fileinput实现文件内容替换,如:file_input.p(注意文件名,别写成fileinput.py

#!/usr/bin/env python
import fileinput
for line in fileinput.input('test.txt',backup='_bak',inplace=1):
  print line.replace('Python','LinuxEye'),
fileinput.close()
Copy after login

inplace=1:标准输出会被重定向到打开文件;backup='_bak',:替换文件内容之前备份后缀以_bak结尾;另外,在调用fileinput.input()之后记得要fileinput.close()。
执行结果如下:

# python file_input.py #执行file_input.py
# ls test.txt*
test.txt test.txt_bak
 
# cat test.txt
Hello,LinuxEye
www.jb51.net
This is a test file
 
# cat test.txt_bak
Hello,Python
www.jb51.net
This is a test file
Copy after login

其他测试:

>>> import fileinput
>>> for line in fileinput.input('test.txt'):
...   print fileinput.filename(),fileinput.lineno(),fileinput.filelineno()
...
test.txt 1 1
test.txt 2 2
test.txt 3 3
Copy after login
>>> import fileinput
>>> for line in fileinput.input('test.txt'):
...   if fileinput.isfirstline():
...     print line,
...   else:
...     break
...
Hello,LinuxEye
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template