Linux 下很多系統管理的工作都會涉及讀取檔案的內容, 在 Python 下可以透過多個方法開啟檔案、讀取 Pipe 及以參數方式讀取檔案。
fileinput 是 Python 的內建模組, 它可以用很簡單的方法, 實現以上的工作。fileinput 模組提供處理一個或多個檔案的功能, 可以是透過 Pipe 輸入、用參數方法指定檔案, 或者在程式碼指定檔案也可以。
以下是 fileinput 模組的使用例子:
|
1 2 3 4 5 6 |
#!/usr/bin/python import fileinput for line in fileinput.input(): print line.replace("\n", "") |
看到上面的程式碼很簡單, 但已經可以將 Pipe 及 參數輸入的檔案讀取, 並逐行印出, 例如:
$ ls | ./test.py
$ ./test.py /etc/passwd
$ ./test.py < /etc/passwd
$ ./test.py /etc/passwd
$ ./test.py < /etc/passwd
上面的例子是透過指令指令讀取的內容, 如果要在程式碼內指定檔案, 只要在 fileinput.input 指定, 可以這樣寫:
|
1 2 3 4 5 6 |
#!/usr/bin/python import fileinput for line in fileinput.input(files='/etc/passwd'): print line.replace("\n", "") |
要同時讀取多個檔案, 只要在 files 指定即可:
|
1 2 3 4 5 6 |
#!/usr/bin/python import fileinput for line in fileinput.input(files=('test.txt', '/etc/passwd')): print line.replace("\n", "") |