Introduction to using the Python fileinput module
- 2020-04-02 14:27:27
- OfStack
The fileinput module provides the ability to process one or more text files by using a for loop to read all lines of one or more text files. It works much like readlines, except that instead of reading all the lines into a list, it creates an xreadlines object.
The following are the common functions in the fileinput module:
input() # Return can be used for for Loop through the object
filename() # Returns the name of the current file
lineno() # Returns the number (or sequence number) of rows currently read
filelineno() # Returns the line number of the currently read line
isfirstline() # Check if the current line is the first line of the file
Create test file test.txt:
# cat > test.txt << EOF
Hello,Python
www.jb51.net
This is a test file
EOF
Use fileinput to replace the contents of the file, such as: file_input.p (note the file name, 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 the open file; Backup ='_bak', : the backup suffix ends with _bak before replacing the contents of the file; Also, remember to use fileinput.close() after calling fileinput.input().
The implementation results are as follows:
# python file_input.py # perform 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
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