Heim  >  Artikel  >  Backend-Entwicklung  >  Python fileinput模块使用介绍

Python fileinput模块使用介绍

WBOY
WBOYOriginal
2016-06-10 15:18:371558Durchsuche

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

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

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

创建测试文件test.txt:

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

利用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()

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

其他测试:

>>> 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
>>> import fileinput
>>> for line in fileinput.input('test.txt'):
...   if fileinput.isfirstline():
...     print line,
...   else:
...     break
...
Hello,LinuxEye
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn