The Fileinput module provides the ability to work with one or more text files, and you can read all the rows of one or more text files by using a For loop. It works the same way as readlines, except that it does not read all the rows to the list but creates a Xreadlines object.
The following are common functions in the Fileinput module:
Input () #返回能够用于for循环遍历的对象
filename () #返回当前文件的名称
Lineno () #返回当前已经读取的行的数量 (or ordinal)
Filelineno () #返回当前读取的行的行号
isfirstline () #检查当前行是否是文件的第一行
To create a test file Test.txt:
# cat > Test.txt << EOF
Hello,Python
www.jb51.net This is
a test file
EOF
Use Fileinput to implement file content substitution, such as: FILE_INPUT.P ( note filename, do not write 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: Standard output will be redirected to open file; backup= ' _bak ': backup suffix to _bak end before replacing file contents, and remember to Fileinput.input () after calling Fileinput.close ().
The results of the implementation are as follows:
# python file_input.py #执行file_input. py
# ls test.txt*
test.txt test.txt_bak
# cat Test.txt
Hello, Linuxeye
www.jb51.net This are
a test file
# cat Test.txt_bak
hello,python
www.jb51.net
This is a test file
Other tests:
>>> 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