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

相關文章
相關標籤/搜索