【Python】将重定向、管道输入或输出文件作为Python脚本的输入

将重定向、管道输入或输出文件作为Python脚本的输入

1. 使用 fileinput 模块来实现

已有文件 file1file2 两个文件,将被作为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):
		"""
		关闭当前文件,读取下一个文件。
		"""
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值