Why can't I join this tuple in Python?

前端 未结 4 1862
不知归路
不知归路 2021-01-31 07:31
e = (\'ham\', 5, 1, \'bird\')
logfile.write(\',\'.join(e))

I have to join it so that I can write it into a text file.

4条回答
  •  迷失自我
    2021-01-31 08:03

    Use the csv module. It will save a follow-up question about how to handle items containing a comma, followed by another about handling items containing the character that you used to quote/escape the commas.

    import csv
    e = ('ham', 5, 1, 'bird')
    with open('out.csv', 'wb') as f:
        csv.writer(f).writerow(e)
    

    Check it:

    print open('out.csv').read()
    

    Output:

    ham,5,1,bird
    

提交回复
热议问题