我想写下面的字符串列表
到csv文件并需要以下目标格式:
Image_URLs,
http://res.cloudinary.com/ddpai9fpa/image/upload/v1516660804/isu8zqke6xoopnemuvvc.jpg,
http://res.cloudinary.com/ddpai9fpa/image/upload/v1516660805/ldie4gmhaqfhw1df1wls.jpg,
http://res.cloudinary.com/ddpai9fpa/image/upload/v1516660805/dvbb5kv3dudxhibqpuni.jpg,
http://res.cloudinary.com/ddpai9fpa/image/upload/v1516660806/inm7ipr8h9ecx1fzcspm.jpg,
http://res.cloudinary.com/ddpai9fpa/image/upload/v1516660806/b6zxz3qntfzrgvinmv3l.jpg,
http://res.cloudinary.com/ddpai9fpa/image/upload/v1516660807/a4qsbfeoujfimzvizwha.jpg,
http://res.cloudinary.com/ddpai9fpa/image/upload/v1516660807/lpqenezik6sy1z9xvtzp.jpg,
摘录
with open(filename, 'w') as myfile:
wr = csv.writer(myfile,lineterminator=',')
wr.writerow('Image_URLs')
wr.writerows(items)
但是,生成以逗号分隔的字符列表,而不是字符串:
I,m,a,g,e,_,U,R,L,s,h,t,t,p,s,:,/,/,u,p,l,o,a,d,.,w,i,k,i,m,e,d,i,a,.,o,r,g,/,w,i,k,i,p,e,d,i,a,/,c,o,m,m,o,n,s,/,t,h,u,m,b,/,6,/,6,6,/,P,o,l,a,r,_,B,e,a,r,_,-,_,A,l,a,s,k,a,_,%,2,8,c,r,o,p,p,e,d,%,2,9,.,j,p,g,/,2,2,0,p,x,-,P,o,l,a,r,_,B,e,a,r,_,-,_,A,l,a,s,k,a,_,%,2,8,c,r,o,p,p,e,d,%,2,9,.,j,p,g,h,t,t,p,s,:,/,/,p,o,l,a,r,b,e,a,r,s,i,n,t,e,r,n,a,t,i,o,n,a,l,.,o,r,g,/,i,m,g,/,e,d,u,-,c,e,n,t,e,r,-,
代码有什么问题?
答案 0 :(得分:2)
该问题的一些评论已经解释了为什么问题正在发生。 完全避免的一种方法是使用Pandas to_csv
()将列表写入CSV文件。
import pandas as pd
# Only included 2 image URLs as an example
items = ['http://res.cloudinary.com/ddpai9fpa/image/upload/v1516660804/isu8zqke6xoopnemuvvc.jpg', 'http://res.cloudinary.com/ddpai9fpa/image/upload/v1516660805/ldie4gmhaqfhw1df1wls.jpg']
items = pd.DataFrame(items, columns=['Image_Urls'])
items.to_csv(file_name, index=False)
答案 1 :(得分:1)
这是一个可以提供帮助的小例子
l = ["A","B","C"]
data = ',\n'.join(l)
f= open("file_name" , "w+")
f.write(data)
f.close()