Why does csvwriter.writerow() put a comma after each character?

前端 未结 3 581
失恋的感觉
失恋的感觉 2020-11-28 05:37

This code opens the url and appends the /names at the end and opens the page and prints the string to test1.csv:

import urllib2
imp         


        
相关标签:
3条回答
  • 2020-11-28 06:02

    The csv.writer class takes an iterable as it's argument to writerow; as strings in Python are iterable by character, they are an acceptable argument to writerow, but you get the above output.

    To correct this, you could split the value based on whitespace (I'm assuming that's what you want)

    csvwriter.writerow(JD.split())
    
    0 讨论(0)
  • 2020-11-28 06:16

    It expects a sequence (eg: a list or tuple) of strings. You're giving it a single string. A string happens to be a sequence of strings too, but it's a sequence of 1 character strings, which isn't what you want.

    If you just want one string per row you could do something like this:

    csvwriter.writerow([JD])
    

    This wraps JD (a string) with a list.

    0 讨论(0)
  • 2020-11-28 06:25

    This happens, because when group() method of a MatchObject instance returns only a single value, it returns it as a string. When there are multiple values, they are returned as a tuple of strings.

    If you are writing a row, I guess, csv.writer iterates over the object you pass to it. If you pass a single string (which is an iterable), it iterates over its characters, producing the result you are observing. If you pass a tuple of strings, it gets an actual string, not a single character on every iteration.

    0 讨论(0)
提交回复
热议问题