open

vim /etc/my.conf

html

使用 open 函数去读取文件,彷佛是全部 Python 工程师的共识。python

今天明哥要给你们推荐一个比 open 更好用、更优雅的读取文件方法 -- 使用 fileinputnginx

fileinput 是 Python 的内置模块,但我相信,很多人对它都是陌生的。今天我把 fileinput 的全部的用法、功能进行详细的讲解,并列举了一些很是实用的案例,对于理解和使用它能够说彻底没有问题。shell

1. 从标准输入中读取#

当你的 Python 脚本没有传入任何参数时,fileinput 默认会以 stdin 做为输入源vim

Copy
Copy
# demo.py import fileinput for line in fileinput.input(): print(line) 

效果以下,无论你输入什么,程序会自动读取并再打印一次,像个复读机似的。bash

Copy
Copy
$ python demo.py hello hello python python 

2. 单独打开一个文件#

脚本的内容以下函数

Copy
Copy
import fileinput with fileinput.input(files=('a.txt',)) as file: for line in file: print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='') 

其中 a.txt 的内容以下ui

Copy
Copy
hello world 

执行后就会输出以下spa

Copy
Copy
$ python demo.py a.txt 第1行: hello a.txt 第2行: world 

须要说明的一点是,fileinput.input() 默认使用 mode='r' 的模式读取文件,若是你的文件是二进制的,能够使用mode='rb' 模式。fileinput 有且仅有这两种读取模式。code

相关文章
相关标签/搜索