PETL documentation规定,为了加载JSON、HTML、XML或text,数据只能来自文件。如何从内存中加载这些格式的数据到PETL中,比如字符串变量,而不是文件?
当加载已经被清理或由上游代码生成的数据时,这将非常有用。仅为了重新读取文件而写入文件是一种浪费且有风险(竞争条件等)的操作。
发布于 2019-02-08 17:39:37
下面的代码有点老生常谈,但至少它避免了向磁盘写入任何内容。
import petl
from io import StringIO
d = '''<table>
<tr>
<td>foo</td><td>bar</td>
</tr>
<tr>
<td>a</td><td>1</td>
</tr>
<tr>
<td>b</td><td>2</td>
</tr>
<tr>
<td>c</td><td>2</td>
</tr>
</table>'''
class OpenableString():
def __init__(self, str):
self.value = StringIO(str)
def open(self, mode):
return self
def __exit__(self, type, value, traceback):
pass
def __enter__(self):
return self.value
os = OpenableString(d)
table1 = petl.fromxml(os, 'tr', 'td')
print(table1)输出:
+-----+-----+
| foo | bar |
+=====+=====+
| a | 1 |
+-----+-----+
| b | 2 |
+-----+-----+
| c | 2 |
+-----+-----+https://stackoverflow.com/questions/54589538
复制相似问题