Python中有FileIO吗?

1 投票
3 回答
7186 浏览
提问于 2025-04-15 13:55

我知道在Python里有一个叫StringIO的流,但Python里有没有文件流呢?还有,查找这些东西有没有更好的方法?比如文档之类的……

我想把一个“流”传给我自己做的一个“写入器”对象。我希望能把一个文件句柄/流传给这个写入器对象。

3 个回答

1

在Python中,所有的输入输出操作都被封装在一个高级接口里,这些接口就像文件一样。

这意味着任何像文件的对象都能以相同的方式工作,可以在需要这些对象的函数中使用。这种方式叫做鸭子类型(duck typing),对于像文件的对象,你可以期待它们有以下的行为:

  • 打开/关闭/输入输出异常
  • 迭代
  • 缓冲
  • 读取/写入/定位

像StringIO、文件和所有类似文件的对象可以互相替换,你不需要自己去管理输入输出。

作为一个小示例,我们来看看你可以用标准输出(stdout)做什么,它也是一个像文件的对象:

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

最后要说的是,虽然它们的工作方式相同,但底层的行为可能并不一样。了解你正在使用的东西是很重要的。在最后一个例子中,在一个网络资源上使用“for”循环是非常危险的,因为你可能会遇到无限的数据流。

在这种情况下,使用:

print steam.read(10000) # another file like object method

会更安全。高级抽象很强大,但并不能让你免于了解这些东西是如何工作的。

5

有一个内置的函数叫做 file(),它的工作方式和其他一些函数差不多。你可以查看这些文档了解更多信息: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 的用法是一样的。

补充一下:你应该使用 open() 而不是 file(),因为它们的用法是一样的,但 file() 在 Python 3 中已经不再使用了。

8

我猜你是在找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

撰写回答