简体   繁体   English

将字符串列表写入csv文件时获取逗号分隔的字符

[英]Getting comma seperated chars when writing list of strings to a csv file

I want to write the following list of strings 我想写下面的字符串列表

在此输入图像描述

To a csv file and need the following target format: 对于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,

The snippet 片段

 with open(filename, 'w') as myfile:
                      wr = csv.writer(myfile,lineterminator=',')
                      wr.writerow('Image_URLs')
                      wr.writerows(items)

however, generates a comma separated list of chars, instead of strings: 但是,生成以逗号分隔的字符列表,而不是字符串:

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,-,

What is wrong with the code? 代码有什么问题?

Some of the comments on the question have explained why the issue is occurring. 关于这个问题的一些评论已经解释了为什么会出现这个问题。 One way to avoid it altogether is to use Pandas to_csv () to write the list to a CSV file. 完全避免它的一种方法是使用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)

Here is small example that can help 这是一个可以提供帮助的小例子

l = ["A","B","C"]
data = ',\n'.join(l)
f= open("file_name" , "w+")
f.write(data)
f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM