Search code examples
pythonpython-3.xlistcsv

List to csv Python


When I try to save a Python list in a csv, the csv have the items that I want to save separated by each character.

I have a list like this with links:

links = ['https://www.portalinmobiliario.com/MLC-2150551226-departamento-los-talaveras-id-117671-_JM#position=1&search_layout=grid&type=item&tracking_id=01bab66e-7cd3-43ce-b3d7-8389260b443d', 
         'https://www.portalinmobiliario.com/MLC-2148268902-departamento-los-espinos-id-116373-_JM#position=2&search_layout=grid&type=item&tracking_id=01bab66e-7cd3-43ce-b3d7-8389260b443d']

Im trying to save this to a csv with this code:

with open('links.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(links)

The result I get from the list is the link in a row but each character in a column.

  • How can I get the links separated by rows but in the same column?

Solution

  • writer.writerows expects the parameter to be an iterable of row lists (quoting the docs: "A row must be an iterable of strings or numbers for Writer objects"); right now it's interpreting your link strings as rows of 1-character columns (since a string is indeed an iterable of strings).

    In short, you'll need to wrap each link in a list (an 1-tuple would do too), e.g. with a generator:

    writer.writerows([link] for link in links)