Oblomov
Oblomov

Reputation: 9635

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

I want to write the following list of strings

enter image description here

To a csv file and need the following target format:

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?

Upvotes: 0

Views: 189

Answers (2)

user3092503
user3092503

Reputation:

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.

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)

Upvotes: 2

Vaibhav Patil
Vaibhav Patil

Reputation: 132

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()

Upvotes: 1

Related Questions