csv.writer writing each character of word in separate column/cell

后端 未结 4 1665
盖世英雄少女心
盖世英雄少女心 2020-12-02 09:27

Objective: To extract the text from the anchor tag inside all lines in models and put it in a csv.

I\'m trying this code:

with open(\'S         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 09:59

    .writerow() requires a sequence ('', (), []) and places each index in it's own column of the row, sequentially. If your desired string is not an item in a sequence, writerow() will iterate over each letter in your string and each will be written to your CSV in a separate cell.

    after you import csv

    If this is your list:

    myList = ['Diamond', 'Sierra', 'Crystal', 'Bridget', 'Chastity', 'Jasmyn', 'Misty', 'Angel', 'Dakota', 'Asia', 'Texxxas', 'Desiree', 'Monique', 'Tatiana']
    
    
    listFile = open('Strippers.csv', 'wb')
    writer = csv.writer(listFile)
    for item in myList:
        writer.writerow(item)
    

    The above script will produce the following CSV: strippers.csv

    D,i,a,m,o,n,d
    S,i,e,r,r,a
    C,r,y,s,t,a,l
    B,r,i,d,g,e,t
    C,h,a,s,t,i,t,y
    J,a,s,m,y,n
    M,i,s,t,y
    A,n,g,e,l
    D,a,k,o,t,a
    A,s,i,a
    T,e,x,x,x,a,s
    D,e,s,i,r,e,e
    M,o,n,i,q,u,e
    T,a,t,i,a,n,a
    

    If you want each name in it's own cell, the solution is to simply place your string (item) in a sequence. Here I use square brackets []. :

    listFile2 = open('Strippers2.csv', 'wb')
    writer2 = csv.writer(listFile2)
    for item in myList:
        writer2.writerow([item])
    

    The script with .writerow([item]) produces the desired results: Strippers2.csv

    Diamond
    Sierra
    Crystal
    Bridget
    Chastity
    Jasmyn
    Misty
    Angel
    Dakota
    Asia
    Texxxas
    Desiree
    Monique
    Tatiana
    

提交回复
热议问题