将重定向、管道输入或输出文件作为Python脚本的输入
1. 使用 fileinput
模块来实现
已有文件 file1
和 file2
两个文件,将被作为Python脚本的输入。
zzz@ubuntu:~/my_learning$ cat file1
This is 1 line.
This is 2 line.
This is 3 line.
This is 4 line.
zzz@ubuntu:~/my_learning$ cat file2
This is an example.
在脚本 fileinput
中,使用 fileinput.input()
创建并返回一个 FileInput
类的实例。可同时接受命令的输出,问价重定向甚至直接在命令行中的一系列文件名。
zzz@ubuntu:~/my_learning$ cat filein.py
import fileinput
with fileinput.input() as f:
for line in f:
print(f.filename(),"--> line ", f.lineno(), " ", line, end='')
zzz@ubuntu:~/my_learning$ python3 filein.py file1 file2
file1 --> line 1 This is 1 line.
file1 --> line 2 This is 2 line.
file1 --> line 3 This is 3 line.
file1 --> line 4 This is 4 line.
file2 --> line 5 This is an example.
zzz@ubuntu:~/my_learning$
2. FileInput
实例
class FileInput(object)
def __init__(self[, files[, inplace[, backup]]], mode=None, openhook=None):
pass
def close(self):
"""
close the sequence.
"""
def filelineno(self):
"""
返回当前读取的文件的行数。
"""
def filename(self):
"""
返回当前读取的文件的文件名。
"""
def fileno(self):
"""
返回读取的文件的数量。
"""
def input(files[, inplace[, backup]], mode=None, openhook=None):
"""
返回一个实例。
"""
def lineno(self):
"""
返回以读取的行数。
"""
def nextfile(self):
"""
关闭当前文件,读取下一个文件。
"""