如何在filefield中将数据帧保存为csv文件



我试图将数据帧保存为模型对象的文件字段中的csv文件,但它没有正确保存,正在保存的文件包含一些其他语言字符!!请告诉我做错了什么??

new_df = df.to_csv(columns=['A', 'B'], index=False)
doc.csvfile.save(f'{doc.id}.csv', ContentFile(new_df))

你好,您可以尝试用以下代码保存csv文件

import csv
from io import StringIO
from django.core.files.base import ContentFile
new_df = df.to_csv(columns=['A', 'B'], index=False)
csv_buffer = StringIO()
csv_writer = csv.writer(csv_buffer)
csv_writer.writerow(new_df)
csv_file = ContentFile(csv_buffer.getvalue().encode('utf-8'))
doc.csvfile.save('output.csv', csv_file)

您可以简单地使用pandas数据帧的to_csv方法在内存中创建一个临时文件。

这里不需要使用任何字符串缓冲机制。

from django.core.files.base import ContentFile
content = df.to_csv(columns=['A', 'B'], index=False)
temp_file = ContentFile(content.encode('utf-8'))
doc.csvfile.save(f'{doc.id}.csv', temp_file)

最新更新