fileinput模塊提供處理一個或多個文本文件的功能, 能夠經過使用for..in來循環讀取一個或多個文本文件內容.python
例子中的文件,app
1.txt
1aless
2a
3a
4a
2.txt
1b
2bide
DESCRIPTION函數
Typical use is:測試
import fileinputthis
for line in fileinput.input():spa
process(line)命令行
This iterates over the lines of all files listed in sys.argv[1:],orm
defaulting to sys.stdin if the list is empty. If a filename is '-' it
is also replaced by sys.stdin. To specify an alternative list of
filenames, pass it as the argument to input(). A single file name is
also allowed.
[譯]這個迭代了全部文件的行在sys.argv[1:]中,若是列表爲空則默認爲標準輸入,若是文件名爲」-」它也爲標準輸入。指定一個文件名列表來作爲參數傳遞給input,一個單獨的文件名也是容許的。
[例]
(1)#!/usr/bin/env python
import fileinput,sys
for line in fileinput.input(sys.argv[1:]):
pass
print fileinput.lineno(),
命令行下,輸入python test.py 1.txt 2.txt
(2)#!/usr/bin/env python
import fileinput
for line in fileinput.input(['1.txt','2.txt']):
pass
print fileinput.lineno(),
(3) #!/usr/bin/env python
import fileinput
for line in fileinput.input(「1.txt」):
pass
print fileinput.lineno(),
Functions filename(), lineno() return the filename and cumulative line
number of the line that has just been read; filelineno() returns its
line number in the current file; isfirstline() returns true iff the
line just read is the first line of its file; isstdin() returns true
iff the line was read from sys.stdin. Function nextfile() closes the
current file so that the next iteration will read the first line from
the next file (if any); lines not read from the file will not count
towards the cumulative line count; the filename is not changed until
after the first line of the next file has been read. Function close()
closes the sequence.
[譯]函數filename,lineno返回的讀取的文件名與已經讀的累計的行數;filelineno返回當前文件的行數的函數;若是讀的是它本身的文件第一行,那麼isfirstline是正確的。若是讀的是來自標準輸入那麼isstdin返回真。函數nextfile關閉當前文件以至下一個迭代器將從下一個文件第一行讀起;將不會累計上一個文件的行數.這個文件名不會改變,直到讀取下一個文件的第一行。函數close關閉序列。
[例]
(1) #!/usr/bin/env python
import fileinput
for line in fileinput.input(['1.txt']):
pass
print fileinput.filename(),fileinput.lineno()
[root@newpatch3 /home/python]#python test.py
1.txt 4
(2) #!/usr/bin/env python
import fileinput
for line in fileinput.input(['1.txt','2.txt']):
pass
print fileinput.filename(),":",fileinput.filelineno()
print "1.txt and 2.txt total line:",fileinput.lineno()
[root@newpatch3 /home/python]#python test.py
2.txt : 2
1.txt and 2.txt total line: 6
你們看到沒,filelineno與lineno的差別了吧?
(3) #!/usr/bin/env python
import fileinput,sys
for line in fileinput.input([‘1.txt’]):
if fileinput.isfirstline():
print line,
sys.exit(0)
[root@newpatch3 /home/python]#python test.py
1a
原1.txt中有1a,2a,3a,4a四行數,但咱們經過條件判斷,只取第一條,來演示isfirstline功能.
(4) #!/usr/bin/env python
import fileinput
for line in fileinput.input():
if fileinput.isstdin():
print "isstdin"
[root@newpatch3 /home/python]#python test.py
This is stdin
Isstdin
Before any lines have been read, filename() returns None and both line
numbers are zero; nextfile() has no effect. After all lines have been
read, filename() and the line number functions return the values
pertaining to the last line read; nextfile() has no effect.
[譯]沒有行讀取前,filename返回None和行號爲0,nextfile也不起做用。在全部行被讀後,filename和獲取行號的函數才能返回到已經讀的當前行。Nextfile才能起做用。
[例]本身測試。
All files are opened in text mode. If an I/O error occurs during
opening or reading a file, the IOError exception is raised.
[譯]全部的文件以文本模式打開,若是在打開或者讀一個文件時發生了一個I/O錯誤,將會產生一個IOError異常。
If sys.stdin is used more than once, the second and further use will
return no lines, except perhaps for interactive use, or if it has been
explicitly reset (e.g. using sys.stdin.seek(0)).
[譯]若是標準輸入用了屢次,第二次將不會返回任何行,除在交互模式下,或者將其重置。
[例]
#!/usr/bin/env python
import fileinput,sys
for line in fileinput.input():
print "line1:",line,
fileinput.close()
sys.stdin.seek(0)
for line in fileinput.input():
print "line2:",line,
fileinput.close()
[root@newpatch3 /home/python]#python test.py
a
b
c
line1: a
line1: b
line1: c
e
f
g
line2: e
line2: f
line2: g
Empty files are opened and immediately closed; the only time their
presence in the list of filenames is noticeable at all is when the
last file opened is empty.
It is possible that the last line of a file doesn't end in a newline
character; otherwise lines are returned including the trailing
newline.
Class FileInput is the implementation; its methods filename(),
lineno(), fileline(), isfirstline(), isstdin(), nextfile() and close()
correspond to the functions in the module. In addition it has a
readline() method which returns the next input line, and a
__getitem__() method which implements the sequence behavior. The
sequence must be accessed in strictly sequential order; sequence
access and readline() cannot be mixed.
[譯]類fileinput是這個的實例;它的方法有filename(),….對應的功能在這個模塊中。除此以外還有readline方法,返回下一行輸入,和__getitem__()方法。該序列中,必須嚴格按順序訪問;序例訪問和readline不能混淆。
Optional in-place filtering: if the keyword argument inplace=1 is
passed to input() or to the FileInput constructor, the file is moved
to a backup file and standard output is directed to the input file.
This makes it possible to write a filter that rewrites its input file
in place. If the keyword argument backup=".<some extension>" is also
given, it specifies the extension for the backup file, and the backup
file remains around; by default, the extension is ".bak" and it is
deleted when the output file is closed. In-place filtering is
disabled when standard input is read. XXX The current implementation
does not work for MS-DOS 8+3 filesystems.
[譯]這段話總的意思是說,inplace若是設爲1,那麼就將讀到的行,輸出到輸入文件中。若是有backup這個參數,就會將源文件內容輸入到備份文件中,輸出還會輸出到輸入文件中。
[例]
(1A)#!/usr/bin/env python
import fileinput,sys
for line in fileinput.input("1.txt", inplace=0):
print line,
[root@newpatch3 /home/python]#python test.py
1a
2a
3a
4a
[root@newpatch3 /home/python]#more 1.txt
1a
2a
3a
4a
(1B) #!/usr/bin/env python
import fileinput,sys
for line in fileinput.input("1.txt",inplace=1):
print 「test」,
[root@newpatch3 /home/python]#python test.py
[root@newpatch3 /home/python]#more 1.txt
test test test test
經過1A與1B能夠發現,咱們若是不指定backup的話,就會將輸出直接寫入到1.txt文件中。
(2) #!/usr/bin/env python
import fileinput,sys
for line in fileinput.input("1.txt",inplace=1,backup=".bak"):
print "test\n",
[root@newpatch3 /home/python]#ls
1.txt 1.txt.bak 2.txt test.py
[root@newpatch3 /home/python]#more 1.txt
test
test
test
test
[root@newpatch3 /home/python]#more 1.txt.bak
1a
2a
3a
4a
Performance: this module is unfortunately one of the slower ways of
processing large numbers of input lines. Nevertheless, a significant
speed-up has been obtained by using readlines(bufsize) instead of
readline(). A new keyword argument, bufsize=N, is present on the
input() function and the FileInput() class to override the default
buffer size.
[譯]對與處理大量的輸入行的處理是不理想的。然而,一個重要的加速已使用readlines(bufsize)來代替ReadLine()。一個新的關鍵參數,bufsize=N,是在input()函數中存在的和FileInput()類中覆蓋buffer size的默認值。總的一句話,經過buffer size這個關鍵函數能夠提升大量的輸入。
若是想了解更多,請關注咱們的公衆號
公衆號ID:opdevos
掃碼關注