我知道在Python中有一個StringIO流,但是在Python中有這樣一個文件流嗎?我還有更好的方式來查找這些東西嗎?文檔等...Python中是否有FileIO?
我想通過一個「流」到我寫的「作家」對象。我希望能將一個文件句柄/流傳遞給這個writer對象。
我知道在Python中有一個StringIO流,但是在Python中有這樣一個文件流嗎?我還有更好的方式來查找這些東西嗎?文檔等...Python中是否有FileIO?
我想通過一個「流」到我寫的「作家」對象。我希望能將一個文件句柄/流傳遞給這個writer對象。
我猜你正在尋找開去()。所有你可以用流做的事情http://docs.python.org/library/functions.html#open
outfile = open("/path/to/file", "w")
[...]
outfile.write([...])
文檔(這些被稱爲「文件對象」或「類文件對象」在Python):http://docs.python.org/library/stdtypes.html#file-objects
有一個內建文件(),其工作方式非常相似。這裏是文檔:http://docs.python.org/library/functions.html#file和http://python.org/doc/2.5.2/lib/bltin-file-objects.html。
如果要打印的文件的所有行做:
for line in file('yourfile.txt'):
print line
當然還有更多,如.seek(),.close().read(),.readlines() ,...與StringIO基本相同的協議。
編輯:不是文件(),它具有相同的API,您應該使用open() - 文件()在Python 3
文件對象記錄在這裏:http://docs.python.org/library/stdtypes.html#bltin-file-objects – tsg
在Python中,所有的I/O操作被包裝在一個高層次的API中:該文件喜歡對象。
這意味着任何文件喜歡對象將表現相同,並可用於期待他們的函數。這就是所謂的鴨子類型,和你一樣可以出現以下行爲的對象文件:
StringIO,File和所有像對象一樣的文件都可以真正被相互替換,並且您不必關心自己管理I/O。
作爲一個小的演示,讓我們看看你可以用標準輸出做什麼,標準輸出,這就好比對象的文件:
import sys
# replace the standar ouput by a real opened file
sys.stdout = open("out.txt", "w")
# printing won't print anything, it will write in the file
print "test"
狀物體的所有文件行爲相同,並且你應該使用它們以同樣的方式:
# try to open it
# do not bother with checking wheter stream is available or not
try :
stream = open("file.txt", "w")
except IOError :
# if it doesn't work, too bad !
# this error is the same for stringIO, file, etc
# use it and your code get hightly flexible !
pass
else :
stream.write("yeah !")
stream.close()
# in python 3, you'd do the same using context :
with open("file2.txt", "w") as stream :
stream.write("yeah !")
# the rest is taken care automatically
注意,就像對象方法的文件共享一個公共的行爲,而是要創建一個類似對象的文件的方式不標準:
import urllib
# urllib doesn't use "open" and doesn't raises only IOError exceptions
stream = urllib.urlopen("www.google.com")
# but this is a file like object and you can rely on that :
for line in steam :
print line
最後一個世界,並不是因爲它的工作原理與基本行爲相同。瞭解你的工作很重要。在最後一個例子中,在Internet資源上使用「for」循環非常危險。事實上,你知道你不會得到無限的數據流。
在這種情況下,使用:
print steam.read(10000) # another file like object method
更安全。高度抽象是強大的,但並不能讓你知道這些東西是如何工作的。
你有權訪問http://www.python.org/doc/?這是查看事物的唯一方法。你現在用什麼來查找東西? –