Python模組學習 Fileinput

2021-09-08 07:18:29 字數 958 閱讀 7413

fileinput是python提供的標準庫,使用fileinput模組可以依次讀取命令列引數中給出的多個檔案。也就是說,它可以遍歷 sys.ar**[1:],並按行讀取列表中的檔案。如果該列表為空,則fileinput預設讀取標準輸入中的內容。

fileinput的使用方法非常簡單,大部分情況下,我們直接呼叫fileinput模組的input方法按行讀取內容即可。

import fileinput

for line in fileinput.input():

print(line,end='')

python3 read_from_fileinput.py  < /etc/hosts

python3 read_from_fileinput.py /etc/hosts

python3 read_from_fileinput.py /etc/hosts /etc/resolv.conf

cat /etc/hosts | python3 read_from_fileinput.py

由於fileinpiut可以讀取多個檔案,所以它提供了一些方法讓我們知道當前讀取的內容屬於哪乙個檔案。

import fileinput

for line in fileinput.input():

meta = [fileinput.filename(),fileinput.fileno(),fileinput.filelineno(),fileinput.isfirstline(),fileinput.isstdin()]

print(line,end='')

print(*meta)

posted @

2017-12-03 00:23

dahlhin 閱讀(

...)

編輯收藏

python學習(模組)

模組搜尋路徑 匯入乙個叫 spam 的模組時,直譯器先在當前目錄中搜尋名為 spam.py 的檔案,然後在環境變數 pythonpath 指琮的目錄列表中搜尋,然後是環境變數 path 中的路徑列表。如果 pythonpath 沒有設定,或者檔案沒有找到,接下來搜尋安裝目錄,在 unix 中,通常是...

python 模組學習

一 from django.contrib.auth.hashers import make password 通過函式名即可發現,主要有兩個函式,分別是建立密碼和驗證 用法ps 123456 dj ps make password ps,none,pbkdf2 sha256 建立django密碼,...

python學習 模組

time import time time.ctime 獲取當前時間的字串 time.localtime 返回值是strcut time型別的物件 st time.localtime st.tm yday 現在是今年第幾天 st.tm hour 現在是今天第幾個小時 st.tm mon 現在是今年的...