我无法打开此上传的csv文件。当我使用pc目录中的文件时,它工作正常,但是当我从html表单上传它时,我收到此错误:
TypeError: coercing to Unicode: need string or buffer, file found
尝试从上传的csv文件中读取时
domain_file = request.POST['csv'].file
file = open(domain_file, "r")
csv_file = csv.reader(file, delimiter=",", quotechar='"')
使用pc
中的文件时,此功能正常 file = open('/Desktop/csv.csv', "r")
csv_file = csv.reader( file, delimiter=",", quotechar='"')
答案 0 :(得分:1)
file
包含文件对象,而不是路径。请改为使用filename
属性:http://flask.pocoo.org/docs/0.10/patterns/fileuploads/
也许是这样的:
domain_file = request.files['csv']
if domain_file and allowed_file(domain_file.filename):
file = open(domain_file, 'r')
#...
另见http://werkzeug.pocoo.org/docs/0.9/wrappers/#werkzeug.wrappers.BaseRequest.files
答案 1 :(得分:1)
如果你这样做,你将能够逐行遍历csv中的数据。
import csv
csv_contents = request.POST['csv'].value.decode('utf-8')
file = csv_contents.splitlines()
data = csv.DictReader(file)