Python 从 Flask 框架编写 CSV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26997679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a CSV from Flask framework
提问by tmthyjames
I have no problems writing a CSV outside of the Flask framework. But when I try to write it from Flask, it writes to the CSV, but only on one line.
我在 Flask 框架之外编写 CSV 没有问题。但是当我尝试从 Flask 写入它时,它会写入 CSV,但只有一行。
Here is the template I'm following
这是我正在关注的模板
@app.route('/download')
def download():
csv = """"REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE"
"1985/01/21","Douglas Adams",0345391802,5.95
"1990/01/12","Douglas Hofstadter",0465026567,9.95
"1998/07/15","Timothy ""The Parser"" Campbell",0968411304,18.99
"1999/12/03","Richard Friedman",0060630353,5.95
"2004/10/04","Randel Helms",0879755725,4.50"""
response = make_response(csv)
response.headers["Content-Disposition"] = "attachment; filename=books.csv"
return response
This writes the CSV perfectly, but when I try with my code, I get one long row.
这完美地写入了 CSV,但是当我尝试使用我的代码时,我得到了一长行。
My code:
我的代码:
@app.route('/download')
def post(self):
# lots of code
csvList.append([all,my,data,goes,here])
csvList = str(re.sub('\[|\]','',str(csvList))) # convert to a string; remove brackets
response = make_response(csvList)
response.headers['Content-Disposition'] = "attachment; filename=myCSV.csv"
return response
My output:
我的输出:
Nashville Physician Service Ce,Treasury Specialist,Brentwood,TN,(615) 507-1646,La Petite Academy,Afternoon Teacher Aide,Goodlettsville,TN,(615) 859-2034,Nashville Physician Service Ce,Denial Resolution Specialist,Brentwood,TN,(615) 507-1646
Thanks.
谢谢。
EDIT:I tried just about all the answers and they worked for the most part, but I chose vectorfrog's because it fit with what I was trying to accomplish.
编辑:我尝试了几乎所有的答案,它们大部分都有效,但我选择了 vectorfrog 的,因为它符合我想要完成的任务。
采纳答案by vectorfrog
I did something like this recently, I found that I needed to first place the csv into a StringIO and then return the StringIO. If you want the csv to be a download, here's what I did:
我最近做了这样的事情,我发现我需要先将csv放入StringIO,然后返回StringIO。如果您希望 csv 成为下载,这就是我所做的:
import StringIO
import csv
from flask import make_response
@app.route('/download')
def post(self):
si = StringIO.StringIO()
cw = csv.writer(si)
cw.writerows(csvList)
output = make_response(si.getvalue())
output.headers["Content-Disposition"] = "attachment; filename=export.csv"
output.headers["Content-type"] = "text/csv"
return output
回答by parchment
You need to add newlines. Anyway, your method of making csvs (printing the list and removing brackets from it) is not the best way to do it. Try this instead:
您需要添加换行符。无论如何,您制作csvs的方法(打印列表并从中删除括号)并不是最好的方法。试试这个:
csvList = '\n'.join(','.join(row) for row in csvList)
Or use the csvmodule:
或者使用csv模块:
import io, csv
dest = io.StringIO()
writer = csv.writer(dest)
for row in csvList:
writer.writerow(row)
# Now dest is a file-like object containing your csv
回答by Oleh Novikov
Since csvis just a plain text format you shoud make shure that new line separator - \nis present at the end of every line you have
由于csv只是纯文本格式,因此您应该使用新行分隔符 -\n出现在您拥有的每一行的末尾
回答by Megatron
I'm not quite sure I understand your objective, but you can try the str.join()method. So, if you wanted to make a quick CSV output from a list of lists:
我不太确定我理解你的目标,但你可以尝试str.join()方法。因此,如果您想从列表列表中快速生成 CSV 输出:
csvList= [['1', '2', '3'], ['4', '5', '6'], ['asdf', '7', 'eight']]
csvStrings= []
for csvLine in csvList:
csvStrings += [",".join(csvLine)]
print "\n".join(csvStrings)
回答by chfw
One alternative::
一种选择::
from flask import Flask, make_response
import pyexcel as pe
import StringIO # py2.7, for python3, please use import io
app = Flask(__name__)
data = [
["REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE"],
["1985/01/21","Douglas Adams",'0345391802',5.95],
["1990/01/12","Douglas Hofstadter",'0465026567',9.95],
["1998/07/15","Timothy \"The Parser\" Campbell",'0968411304',18.99],
["1999/12/03","Richard Friedman",'0060630353',5.95],
["2004/10/04","Randel Helms",'0879755725',4.50]
]
@app.route('/download')
def download():
sheet = pe.Sheet(data)
io = StringIO.StringIO()
sheet.save_to_memory("csv", io)
output = make_response(io.getvalue())
output.headers["Content-Disposition"] = "attachment; filename=export.csv"
output.headers["Content-type"] = "text/csv"
return output
if __name__ == "__main__":
app.debug=True
app.run()
Another alternative is to use Flask-Excel:
另一种选择是使用 Flask-Excel:
from flask import Flask, make_response
from flask.ext import excel
app = Flask(__name__)
data = [
["REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE"],
["1985/01/21","Douglas Adams",'0345391802',5.95],
["1990/01/12","Douglas Hofstadter",'0465026567',9.95],
["1998/07/15","Timothy \"The Parser\" Campbell",'0968411304',18.99],
["1999/12/03","Richard Friedman",'0060630353',5.95],
["2004/10/04","Randel Helms",'0879755725',4.50]
]
@app.route('/download')
def download():
output = excel.make_response_from_array(data, 'csv')
output.headers["Content-Disposition"] = "attachment; filename=export.csv"
output.headers["Content-type"] = "text/csv"
return output
if __name__ == "__main__":
app.debug=True
app.run()

