我有一些遺留代碼與傳統函數,將文件名作爲參數並處理文件內容。代碼的工作傳真如下。StringIO與'與'語句的兼容性(上下文管理器)
我想要做的就是不必爲了使用這個遺留功能而生成的一些內容寫入磁盤,所以我可以使用StringIO
來創建一個對象來代替物理文件名。但是,這不起作用,如下所示。我認爲StringIO
是這樣的方式。任何人都可以告訴我,如果有一種方法可以使用這個遺留函數,並將它傳遞給不是磁盤上文件的參數,而是可以通過遺留函數來處理?舊功能的with
上下文管理器正在處理filename
參數值。
我在谷歌遇到的一兩件事是: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
你不能「打開」一個StringIO的實例 – 2012-08-09 22:07:15