栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

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

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

将重定向、管道输入或输出文件作为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):
		"""
		关闭当前文件,读取下一个文件。
		"""
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/974683.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号