The Fileinput module provides the ability to work with one or more text files, and you can read all lines of one or more text files by using a For loop. It works in a similar way to 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 () # Returns the line number of the currently read Line Isfirstline () #检查当前行是否是文件的第一行
To create a test file Test.txt:
# cat > Test.txt << eofhello,Pythonwww.jb51.netThis is a test fileeof
Use Fileinput to implement the file content substitution, such as: FILE_INPUT.P ( note The file name, do not write fileinput.py)
#!/usr/bin/env pythonimport fileinputfor 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 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.txthello,linuxeyewww.jb51.netthis is a test file # cat test.txt_bakhello,pythonwww.jb51.netthis is a test file
Other tests:
>>> Import fileinput>>> in Fileinput.input (' Test.txt '): ... Print Fileinput.filename (), Fileinput.lineno (), Fileinput.filelineno () ... test.txt 1 1test.txt 2 2test.txt 3 3
>>> Import fileinput>>> in Fileinput.input (' Test.txt '): ... If Fileinput.isfirstline (): ... Print Line,... else: ... Break ... Hello,linuxeye