我对python很陌生。我有一个csv格式的股票名称列表。我提取名称并将其放在网站域名之前以创建url。我试图将我创建的url写入另一个csv,但它只写入列表中的最后一个。我想让它把所有的url写入csv文件
with open('names.csv', 'r') as datafile:
for line in datafile:
domain = f'https://ceo.ca/{line}'
urls_link = (domain.strip())
print(urls_link)
y = open("url.csv","w")
y.writelines(urls_link)
y.close()
names.csv: https://i.stack.imgur.com/WrrLw.pngurl.csv: https://i.stack.imgur.com/BYEgN.png我想要url csv看起来像这样:https://i.stack.imgur.com/y4xre.png如果我说了一些难听的话,我道歉。
您可以在python中使用csv
模块
试试下面的代码:
from csv import writer,reader
in_FILE = "names.csv"
out_FILE = 'url.csv'
urls = list()
with open(in_FILE, 'r') as infile:
read = reader(infile, delimiter=",")
for domain_row in read:
for domain in domain_row:
url = f'https://ceo.ca/{domain.strip()}'
urls.append(url)
with open(out_FILE, 'w') as outfile:
write = writer(outfile)
for url in urls:
write.writerow([url])