我正在尝试使用 for 循环将一组 Python URL 转换为 .csv 文件。 我正在使用Python 3.8。该集包含 116 个唯一的 URL。但是,我的输出.csv文件中有超过 6000 个逗号分隔值。
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()
如果你想要一行和多列:
with open('task_links.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(list(myset))
如果你想要一列和多行
with open('task_links.csv', 'w') as f:
writer = csv.writer(f)
for url in myset:
writer.writerow([url])
您将集合中的每个URL附加到mylist
然后将整个列表写入CSV文件中。这应该有效:
c = open('task_links.csv', 'w')
cw = csv.writer(c, lineterminator='')
mylist = []
for x in myset:
mylist.append(x)
cw.writerow(x)
c.close()
如果你不反对熊猫套餐
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)