我编写了一个函数,将查询集转换为CSV文件,然后通过电子邮件发送给用户。因为不需要在系统上存储文件,所以我决定使用Tempfile对象。 然而,尽管我成功地写了这些对象,我无法阅读它们-这阻止了我通过电子邮件将它们作为附件
columns = instances[0].get_columns
# create tempfile, in TEXT (t) mode so as not to trip up the
# csv module, which cant handle binary data.
file = tempfile.NamedTemporaryFile(mode='wt')
try:
writer = csv.writer(file)
writer.writerow([field[0] for field in columns])
for instance in instances:
row = [getattr(instance, str(field[0])) for field in columns]
# email the file
body = 'The exported file has been included as a attachment.'
email = EmailMessage(
subject='CSV Export',
from_email='******',
to=['*****'],
body=body,
)
email.attach('export.csv', file, 'text/csv')
email.send()
这将触发以下错误: '_io.TextIOWrapper'对象没有属性'splitlines'
经过一番谷歌搜索,我似乎不得不.read()
文件
但是,新代码(email.attach('export.csv', file.read(), 'text/csv')
unportedOperation:notreadable`错误。在
其他帖子建议,除了.read()之外,我需要使用file.seek(0, os.SEEK_END)
来“倒带”文件,但是not readable error
一直在触发。在
如果我删除file.read()
而保留{'_io.TextIOWrapper' object has no attribute 'splitlines'
错误。在
有人知道我做错了什么吗?在
目前没有回答
相关问题 更多 >
编程相关推荐