我想将数据[1,2,'a','He said "what do you mean?"']转换为csv格式的字符串.
通常人们可以使用csv.writer()它,因为它处理所有疯狂的边缘情况(逗号转义,引用标记转义,CSV方言等).捕获是csv.writer()期望输出到文件对象,而不是字符串.
我目前的解决方案是这个有点hacky函数:
def CSV_String_Writeline(data):
class Dummy_Writer:
def write(self,instring):
self.outstring = instring.strip("\r\n")
dw = Dummy_Writer()
csv_w = csv.writer( dw )
csv_w.writerow(data)
return dw.outstring
Run Code Online (Sandbox Code Playgroud)
任何人都可以提供更优雅的解决方案,仍能很好地处理边缘情况吗?
编辑:这是我最终如何做到这一点:
def csv2string(data):
si = StringIO.StringIO()
cw = csv.writer(si)
cw.writerow(data)
return si.getvalue().strip('\r\n')
Run Code Online (Sandbox Code Playgroud) 我刚开始使用Flask/Python.我想要实现的是我的HTML中有一个下载按钮,它调用以下函数:
function downloadPlotCSV() {
$.ajax({
url: "/getPlotCSV",
type: "post",
success: function(data) {
dataPlot = JSON.parse(data);
console.log(dataPlot);
}
});
}
Run Code Online (Sandbox Code Playgroud)
不完整的烧瓶代码是:
@app.route('/getPlotCSV', methods = ['POST'])
def plotCSV():
data = open("outputs/Adjacency.csv")
Run Code Online (Sandbox Code Playgroud)
我面临的问题是我找不到下载此csv文件或将其作为JSON字符串返回的方法,因此我可以使用Javascript下载它.知道如何将其作为JSON发送或者通过Flask本身下载它吗?什么是最好的方式?
我有一个example.csv包含内容的文件
1,"A towel,",1.0
42," it says, ",2.0
1337,is about the most ,-1
0,massively useful thing ,123
-2,an interstellar hitchhiker can have.,3
Run Code Online (Sandbox Code Playgroud)
我如何example.csv用Python 阅读?
同样,如果我有
data = [(1, "A towel,", 1.0),
(42, " it says, ", 2.0),
(1337, "is about the most ", -1),
(0, "massively useful thing ", 123),
(-2, "an interstellar hitchhiker can have.", 3)]
Run Code Online (Sandbox Code Playgroud)
如何data使用Python 写入CSV文件?
在Flask框架之外编写CSV没有问题.但是当我尝试从Flask写入它时,它会写入CSV,但只能在一行上写入.
这是我正在关注的模板
@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
Run Code Online (Sandbox Code Playgroud)
这完全可以写入CSV,但是当我尝试使用我的代码时,我会得到一个长行.
我的代码:
@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
Run Code Online (Sandbox Code Playgroud)
我的输出:
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
Run Code Online (Sandbox Code Playgroud)
谢谢.
编辑:我尝试了所有的答案,他们在大多数情况下工作,但我选择了vectorfrog,因为它符合我想要完成的任务.