简体   繁体   中英

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

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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