2009-08-27 27 views
1

我知道在Python中有一个StringIO流,但是在Python中有这样一个文件流吗?我还有更好的方式来查找这些东西吗?文档等...Python中是否有FileIO?

我想通过一个“流”到我写的“作家”对象。我希望能将一个文件句柄/流传递给这个writer对象。

+2

你有权访问http://www.python.org/doc/?这是查看事物的唯一方法。你现在用什么来查找东西? –

回答

5

有一个内建文件(),其工作方式非常相似。这里是文档:http://docs.python.org/library/functions.html#filehttp://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

+0

文件对象记录在这里:http://docs.python.org/library/stdtypes.html#bltin-file-objects – tsg

1

在Python中,所有的I/O操作被包装在一个高层次的API中:该文件喜欢对象。

这意味着任何文件喜欢对象将表现相同,并可用于期待他们的函数。这就是所谓的鸭子类型,和你一样可以出现以下行为的对象文件:

  • 开启/关闭/ IO异常
  • 迭代
  • 缓冲
  • 读/写/寻求

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 

更安全。高度抽象是强大的,但并不能让你知道这些东西是如何工作的。