【发布时间】:2009-08-27 20:48:47
【问题描述】:
我知道 Python 中有一个 StringIO 流,但是 Python 中有文件流之类的东西吗?我还有更好的方法来查找这些东西吗?文档等...
我正在尝试将“流”传递给我制作的“作家”对象。我希望我可以将文件句柄/流传递给这个 writer 对象。
【问题讨论】:
-
你可以访问python.org/doc吗?这是查看事情的唯一方法。你现在用什么来查资料?
我知道 Python 中有一个 StringIO 流,但是 Python 中有文件流之类的东西吗?我还有更好的方法来查找这些东西吗?文档等...
我正在尝试将“流”传递给我制作的“作家”对象。我希望我可以将文件句柄/流传递给这个 writer 对象。
【问题讨论】:
我猜你正在寻找 open()。 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
【讨论】:
有一个内置的 file() 的工作方式大致相同。以下是文档: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 的协议基本相同。
编辑:您应该使用 open() 而不是 file(),它具有相同的 API - file() 在 Python 3 中使用。
【讨论】:
在 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
更安全。高度抽象很强大,但不会让您无需了解这些东西是如何工作的。
【讨论】: