我有一些遗留的代码,其中包括一个以文件名作为参数并处理文件内容的遗留函数。下面是一个可行的代码示例。
我想做的是不必将我生成的某些内容写入磁盘,就可以使用这个遗留函数。因此,我认为可以使用 StringIO
来创建一个对象来代替实际的文件名。但是,如下所示,这样做是行不通的。
我认为使用 StringIO
是合适的方法。有没有人能告诉我是否有一种方法可以在参数中传递不是磁盘上的文件,但是可以被这个遗留函数视为这样的东西?该遗留函数确实对 filename
参数值使用了 with
上下文管理器进行操作。
我在 Google 上找到的唯一一件事是:http://bugs.python.org/issue1286,但这并没有帮助我解决问题...
代码
from pprint import pprint
import StringIO
# Legacy Function
def processFile(filename):
with open(filename, 'r') as fh:
return fh.readlines()
# This works
print 'This is the output of FileOnDisk.txt'
pprint(processFile('c:/temp/FileOnDisk.txt'))
print
# This fails
plink_data = StringIO.StringIO('StringIO data.')
print 'This is the error.'
pprint(processFile(plink_data))
输出
这是存储在 FileOnDisk.txt
文件中的输出内容:
['This file is on disk.\n']
这是错误信息:
Traceback (most recent call last):
File "C:\temp\test.py", line 20, in <module>
pprint(processFile(plink_data))
File "C:\temp\test.py", line 6, in processFile
with open(filename, 'r') as fh:
TypeError: coercing to Unicode: need string or buffer, instance found
delete=False
参数,因此命名临时文件在关闭后 不会 立即被删除 —— 请参阅 文档。从yield temp.name
语句之前的temp.close()
可以看出这一点... - martineau.close()
将清除为内存文件数据分配的内存缓冲区。 - Martijn Pieterstempinput()
上下文管理器来提供指向带有给定数据的临时文件的文件名。 - Martijn Pieters