-1

I am very new to python. I have a list of stock names in a csv. I extract the names and put it before a website domain to create urls. I am trying to write the urls I created into another csv, but it only writes the last one out of the list. I want it to write all of the url into the 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.png url.csv: https://i.stack.imgur.com/BYEgN.png I would want the url csv look like this: https://i.stack.imgur.com/y4xre.png I apologise if I worded some things horribly.

  • 1
    Does this answer your question? [Writing a Python list of lists to a csv file](https://stackoverflow.com/questions/14037540/writing-a-python-list-of-lists-to-a-csv-file) – Rustam A. Aug 25 '21 at 21:41
  • 1
    Write your urllink *inside* the loop, otherwise it only writes the last one. – Mark Tolonen Aug 25 '21 at 21:55
  • Read [this article](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) for tips on debugging your code. This is a critical skill to learn so that you can track down problems in the code you write. – Code-Apprentice Aug 25 '21 at 22:16

1 Answers1

0

You can use csv module in python

Try using this code:

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])
Ahmed
  • 16