Introduction to the Python fileinput module, pythonfileinput
The fileinput module allows you to process one or more text files. You can use the for loop to read all rows of one or more text files. It works in a similar way as readlines. The difference is that it creates an xreadlines object instead of reading all rows into the list.
The following are common functions in the fileinput module:
Input () # returns the object filename () that can be used for loop traversal # returns the name of the current file lineno () # returns the number (or serial number) of currently read rows filelineno () # Return the row number isfirstline () of the currently read row # Check whether the current row is the first row of the file
Create the test file test.txt:
# cat > test.txt << EOFHello,Pythonwww.jb51.netThis is a test fileEOF
Use fileinput to replace the file content, for example, file_input.p (note that the file name should not be written as 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: The standard output will be redirected to the open file; backup = '_ Bak': the backup suffix ends with _ bak before the file content is replaced; in addition, fileinput is called. remember fileinput after input. close ().
The execution result is as follows:
# Python file_input.py # Run file_input.py # ls test.txt * test.txt _ bak # cat test.txt Hello, LinuxEyewww. Metadata is a test file # cat test.txt _ bakHello, Pythonwww. jb51.netThis 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 1test.txt 2 2test.txt 3 3
>>> import fileinput>>> for line in fileinput.input('test.txt'):... if fileinput.isfirstline():... print line,... else:... break...Hello,LinuxEye