Gene Butler
Gene Butler

Reputation: 13

Converting set to .csv using for loop

I am trying to convert a Python set of URLs to a .csv file using a for loop. I'm using Python 3.8. The set contains 116 unique URL's. However, my output .csv file has over 6000 comma-separated values in the file.

c = open('task_links.csv', 'w')
cw = csv.writer(c, lineterminator='')
mylist = []
for x in myset:
    mylist.append(x)
    if not mylist:
        continue
    else:
        cw.writerow(mylist)
c.close()

Upvotes: 0

Views: 2042

Answers (3)

Tim
Tim

Reputation: 2637

If you want one row and multiple columns:

with open('task_links.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow(list(myset))

If you want one column and multiple rows

with open('task_links.csv', 'w') as f:
    writer = csv.writer(f)
    for url in myset:
        writer.writerow([url])

Upvotes: 1

kbakes
kbakes

Reputation: 1

If you are not opposed to the pandas packages

import pandas as pd

set_of_links = set(["https://www.link{}.com".format(i) for i in range(116)])
df = pd.DataFrame(set_of_links, columns=['links'])
df.to_csv('task_links.csv', index=False)

Upvotes: 0

aminrd
aminrd

Reputation: 5050

You are appending each URL in your set to mylist and then writing the whole list into your CSV file. This should work:

c = open('task_links.csv', 'w')
cw = csv.writer(c, lineterminator='')
mylist = []
for x in myset:
    mylist.append(x)
    cw.writerow(x)
c.close()

Upvotes: 0

Related Questions