【发布时间】:2013-06-19 04:32:36
【问题描述】:
我正在尝试通过 Django 应用将 CSV 文件上传到 Google App Engine 中的 blobstore 文件中。我遇到了一个问题,即在上传文件时转储文件可能会出现错误的换行符。所以,我需要在 python 的通用换行模式下打开上传的文件。 Django 文档建议我可以在 File 对象上使用 .open() 来设置新模式。
这是我提出的解决方案:
filename = files.blobstore.create(mime_type='text/csv')
csvfile = request.FILES.get('csvfile')
with files.open(filename, 'a') as output_file:
with csvfile.open(mode='rU') as input_file:
output_file.write(input_file.readline())
(“文件”是 App Engine 的 API 的一部分)
这对我来说似乎是正确的,但我想知道是否有其他人遇到过类似的情况和更好的解决方案?
【问题讨论】:
-
FWIW,上面的代码在 csvfile 的上下文管理器的 exit 上给了我一个例外。也许我需要手动打开和关闭它?目前尚不完全清楚我什至想做的事情是否可以通过the documentation 实现。
-
这是一个例外,对我来说这表明 Django 的 files.File 类没有实现上下文管理器协议,也许吧?即使它是 Python 文件对象的包装器?
with csvfile.open(mode='rU') as input_file: AttributeError: __exit__
标签: python django google-app-engine csv blobstore