一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - Python讀取文件比open快十倍的庫fileinput

Python讀取文件比open快十倍的庫fileinput

2022-02-18 00:06寫代碼的明哥 Python

fileinput是Python的內置模塊,但不少人對它都是陌生的。今天把fileinput的所有的用法、功能進行詳細的講解,并列舉一些非常實用的案例,對于理解和使用它可以說完全沒有問題

使用 open 函數去讀取文件,似乎是所有 Python 工程師的共識。

今天明哥要給大家推薦一個比 open 更好用、更優雅的讀取文件方法 – 使用 fileinput

1. 從標準輸入中讀取

當你的 Python 腳本沒有傳入任何參數時,fileinput 默認會以 stdin 作為輸入源

?
1
2
3
4
5
# demo.py
import fileinput
 
for line in fileinput.input():
    print(line)

效果如下,不管你輸入什么,程序會自動讀取并再打印一次,像個復讀機似的。

?
1
2
3
4
5
6
$ python demo.py
hello
hello
 
python
python

2. 單獨打開一個文件

腳本的內容如下

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

其中 a.txt 的內容如下

hello
world

執行后就會輸出如下

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

需要說明的一點是,fileinput.input() 默認使用 mode='r' 的模式讀取文件,如果你的文件是二進制的,可以使用mode='rb' 模式。fileinput 有且僅有這兩種讀取模式。

3. 批量打開多個文件

從上面的例子也可以看到,我在 fileinput.input 函數中傳入了 files 參數,它接收一個包含多個文件名的列表或元組,傳入一個就是讀取一個文件,傳入多件就是讀取多個文件。

?
1
2
3
4
5
import fileinput
 
with fileinput.input(files=('a.txt', 'b.txt')) as file:
    for line in file:
        print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='')

a.txtb.txt 的內容分別是

?
1
2
3
4
5
6
$ cat a.txt
hello
world
$ cat b.txt
hello
python

運行后輸出結果如下,由于 a.txtb.txt 的內容被整合成一個文件對象 file ,因此 fileinput.lineno() 只有在讀取一個文件時,才是原文件中真實的行號。

?
1
2
3
4
5
$ python demo.py
a.txt 第1行: hello
a.txt 第2行: world
b.txt 第3行: hello
b.txt 第4行: python

如果想要在讀取多個文件的時候,也能讀取原文件的真實行號,可以使用 fileinput.filelineno() 方法

?
1
2
3
4
5
import fileinput
 
with fileinput.input(files=('a.txt', 'b.txt')) as file:
    for line in file:
        print(f'{fileinput.filename()} 第{fileinput.filelineno()}行: {line}', end='')

運行后,輸出如下

?
1
2
3
4
5
$ python demo.py
a.txt 第1行: hello
a.txt 第2行: world
b.txt 第1行: hello
b.txt 第2行: python

這個用法和 glob 模塊簡直是絕配

?
1
2
3
4
5
6
7
import fileinput
import glob
 
for line in fileinput.input(glob.glob("*.txt")):
    if fileinput.isfirstline():
        print('-'*20, f'Reading {fileinput.filename()}...', '-'*20)
    print(str(fileinput.lineno()) + ': ' + line.upper(), end="")

運行效果如下

?
1
2
3
4
5
6
7
$ python demo.py
-------------------- Reading b.txt... --------------------
1: HELLO
2: PYTHON
-------------------- Reading a.txt... --------------------
3: HELLO
4: WORLD

4. 讀取的同時備份文件

fileinput.input 有一個 backup 參數,你可以指定備份的后綴名,比如 .bak

?
1
2
3
4
import fileinput
with fileinput.input(files=("a.txt",), backup=".bak") as file:
    for line in file:
        print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='')

運行的結果如下,會多出一個 a.txt.bak 文件

?
1
2
3
4
5
6
7
8
9
10
$ ls -l a.txt*
-rw-r--r--  1 MING  staff  12  2 27 10:43 a.txt
 
$ python demo.py
a.txt 第1行: hello
a.txt 第2行: world
 
$ ls -l a.txt*
-rw-r--r--  1 MING  staff  12  2 27 10:43 a.txt
-rw-r--r--  1 MING  staff  42  2 27 10:39 a.txt.bak

5. 標準輸出重定向替換

fileinput.input 有一個 inplace 參數,表示是否將標準輸出的結果寫回文件,默認不取代

請看如下一段測試代碼

?
1
2
3
4
5
6
7
import fileinput
 
with fileinput.input(files=("a.txt",), inplace=True) as file:
    print("[INFO] task is started...")
    for line in file:
        print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='')
    print("[INFO] task is closed...")

運行后,會發現在 for 循環體內的 print 內容會寫回到原文件中了。而在 for 循環體外的 print 則沒有變化。

?
1
2
3
4
5
6
7
8
9
10
11
$ cat a.txt
hello
world
 
$ python demo.py
[INFO] task is started...
[INFO] task is closed...
 
$ cat a.txt
a.txt 第1行: hello
a.txt 第2行: world

利用這個機制,可以很容易的實現文本替換。

?
1
2
3
4
5
6
7
8
import sys
import fileinput
 
for line in fileinput.input(files=('a.txt', ), inplace=True):
    #將Windows/DOS格式下的文本文件轉為Linux的文件
    if line[-2:] == "\r\n"
        line = line + "\n"
    sys.stdout.write(line)

附:如何實現 DOS 和 UNIX 格式互換以供程序測試,使用 vim 輸入如下指令即可

DOS轉UNIX::setfileformat=unix
UNIX轉DOS::setfileformat=dos

6. 不得不介紹的方法

如果只是想要 fileinput 當做是替代 open 讀取文件的工具,那么以上的內容足以滿足你的要求。

fileinput.filenam()
返回當前被讀取的文件名。 在第一行被讀取之前,返回 None

fileinput.fileno()
返回以整數表示的當前文件“文件描述符”。 當未打開文件時(處在第一行和文件之間),返回 -1

fileinput.lineno()
返回已被讀取的累計行號。 在第一行被讀取之前,返回 0。 在最后一個文件的最后一行被讀取之后,返回該行的行號。

fileinput.filelineno()
返回當前文件中的行號。 在第一行被讀取之前,返回 0。 在最后一個文件的最后一行被讀取之后,返回此文件中該行的行號。

但若要想基于 fileinput 來做一些更加復雜的邏輯,也許你會需要用到如下這幾個方法

fileinput.isfirstline()
如果剛讀取的行是其所在文件的第一行則返回 True,否則返回 False

fileinput.isstdin()
如果最后讀取的行來自 sys.stdin 則返回 True,否則返回 False

fileinput.nextfile()
關閉當前文件以使下次迭代將從下一個文件(如果存在)讀取第一行;不是從該文件讀取的行將不會被計入累計行數。 直到下一個文件的第一行被讀取之后文件名才會改變。 在第一行被讀取之前,此函數將不會生效;它不能被用來跳過第一個文件。 在最后一個文件的最后一行被讀取之后,此函數將不再生效。

fileinput.close()關閉序列。

7. 進階一點的玩法

fileinput.input() 中有一個 openhook 的參數,它支持用戶傳入自定義的對象讀取方法。

若你沒有傳入任何的勾子,fileinput 默認使用的是 open 函數。

Python讀取文件比open快十倍的庫fileinput

fileinput 為我們內置了兩種勾子供你使用

1. fileinput.hook_compressed(*filename*, *mode*)

使用 gzipbz2 模塊透明地打開 gzip 和 bzip2 壓縮的文件(通過擴展名 '.gz''.bz2' 來識別)。 如果文件擴展名不是 '.gz''.bz2',文件會以正常方式打開(即使用 open() 并且不帶任何解壓操作)。使用示例:

 fi = fileinput.FileInput(openhook=fileinput.hook_compressed)

2.  fileinput.hook_encoded(*encoding*, *errors=None*)

返回一個通過 open() 打開每個文件的鉤子,使用給定的 encoding 和 errors 來讀取文件。使用示例:

 fi = fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8", "surrogateescape"))

如果你自己的場景比較特殊,以上的三種勾子都不能滿足你的要求,你也可以自定義。

這邊我舉個例子來拋磚引玉下

假如我想要使用 fileinput 來讀取網絡上的文件,可以這樣定義勾子。

先使用 requests 下載文件到本地

再使用 open 去讀取它

?
1
2
3
4
5
6
7
8
def online_open(url, mode):
    import requests
    r = requests.get(url)
    filename = url.split("/")[-1]
    with open(filename,'w') as f1:
        f1.write(r.content.decode("utf-8"))
    f2 = open(filename,'r')
    return f2

直接將這個函數傳給 openhoos 即可

?
1
2
3
4
5
6
import fileinput
 
file_url = 'https://www.csdn.net/robots.txt'
with fileinput.input(files=(file_url,), openhook=online_open) as file:
    for line in file:
        print(line, end="")

運行后按預期一樣將 CSDN 的 robots 的文件打印了出來

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
User-agent: *
Disallow: /scripts
Disallow: /public
Disallow: /css/
Disallow: /images/
Disallow: /content/
Disallow: /ui/
Disallow: /js/
Disallow: /scripts/
Disallow: /article_preview.html*
Disallow: /tag/
Disallow: /*?*
Disallow: /link/
 
Sitemap: https://www.csdn.net/sitemap-aggpage-index.xml
Sitemap: https://www.csdn.net/article/sitemap.txt

8. 列舉一些實用案例

案例一:讀取一個文件所有行

?
1
2
3
import fileinput
for line in fileinput.input('data.txt'):
  print(line, end="")

案例二:讀取多個文件所有行

?
1
2
3
4
5
6
7
import fileinput
import glob
 
for line in fileinput.input(glob.glob("*.txt")):
    if fileinput.isfirstline():
        print('-'*20, f'Reading {fileinput.filename()}...', '-'*20)
    print(str(fileinput.lineno()) + ': ' + line.upper(), end="")

案例三:利用fileinput將CRLF文件轉為LF

?
1
2
3
4
5
6
7
8
import sys
import fileinput
 
for line in fileinput.input(files=('a.txt', ), inplace=True):
    #將Windows/DOS格式下的文本文件轉為Linux的文件
    if line[-2:] == "\r\n"
        line = line + "\n"
    sys.stdout.write(line)

案例四:配合 re 做日志分析:取所有含日期的行

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#--樣本文件--:error.log
aaa
1970-01-01 13:45:30  Error: **** Due to System Disk spacke not enough...
bbb
1970-01-02 10:20:30  Error: **** Due to System Out of Memory...
ccc
 
#---測試腳本---
import re
import fileinput
import sys
 
pattern = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'
 
for line in fileinput.input('error.log',backup='.bak',inplace=1):
    if re.search(pattern,line):
        sys.stdout.write("=> ")
        sys.stdout.write(line)
 
#---測試結果---
=> 1970-01-01 13:45:30  Error: **** Due to System Disk spacke not enough...
=> 1970-01-02 10:20:30  Error: **** Due to System Out of Memory...

案例五:利用fileinput實現類似于grep的功能

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import sys
import re
import fileinput
 
pattern= re.compile(sys.argv[1])
for line in fileinput.input(sys.argv[2]):
    if pattern.match(line):
        print(fileinput.filename(), fileinput.filelineno(), line)
$ ./test.py import.*re *.py
#查找所有py文件中,含import re字樣的
addressBook.py  2   import re
addressBook1.py 10  import re
addressBook2.py 18  import re
test.py         238 import re

9. 寫在最后

fileinput 是對 open 函數的再次封裝,在僅需讀取數據的場景中, fileinput 顯然比 open 做得更專業、更人性,當然在其他有寫操作的復雜場景中,fileinput 就無能為力啦,本身從 fileinput 的命名上就知道這個模塊只專注于輸入(讀)而不是輸出(寫)。

以上就是Python讀取文件比open快十倍的庫fileinput的詳細內容,更多關于Python讀取文件庫fileinput的資料請關注服務器之家其它相關文章!

原文鏈接:https://blog.csdn.net/weixin_36338224/article/details/114282594

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 色姑娘色综合 | 四虎1515hhc0m | 荡娃艳妇有声小说 | 欧美在线视频7777kkkk | 国内揄拍国内精品久久 | 嫩草香味 | 日韩精品在线一区二区 | 性吧有你 | 公交车揉捏大乳呻吟喘娇 | 91桃色视频 | 亚洲国产精品无码中文在线 | 4虎影视国产在线观看精品 4s4s4s4s色大众影视 | 亚洲成年人免费网站 | 亚洲精品黄色 | 日本高免费观看在线播放 | 日本私人影院 | 岛国不卡| 美女奶口隐私免费视频网站 | 国产成人亚洲精品91专区手机 | 国产精品久久国产三级国电话系列 | 男人操男人 | 午夜看片a福利在线观看 | 好涨好大我快受不了了视频网 | 色橹橹| 特黄特a级特别特级特毛片 特黄a级三级三级野战 | 精品亚洲456在线播放 | 欧美日韩视频在线成人 | 国产精品自在线拍 | 免费岛国片 | 1024免费福利永久观看网站 | 国产欧美日韩精品在线 | 欧美黑人换爱交换乱理伦片 | 91探花在线播放 | caoporn人人 | 国产a在线 | 海绵宝宝第二季全集免费观看 | 精品AV无码一二三区视频 | 99re这里只有精品视频在线观看 | 丝瓜视频看污片 | 国产男女性特黄录像 | 国产精选之刘婷野战 |