How to read a csv file with python

前端 未结 3 1227
北荒
北荒 2020-12-16 07:18

I\'m trying to read a csv file but it doesn\'t work. I can read my csv file but when I see what I read, there where white space between values.

Here is my code

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 07:47

    If you have control over the data, use tab-delimited instead::

    import csv
    import string
    
    writer = open('junk.txt', 'wb')
    for x in range(10):
        writer.write('\t'.join(string.letters[:5]))
        writer.write('\r\n')
    writer.close()
    reader = csv.reader(open('junk.txt', 'r'), dialect='excel-tab')
    for line in reader:
        print line
    

    This produces expected results.

    A tip for getting more useful feedback: Demonstrate your problem through self-contained and complete example code that doesn't contain extraneous and unimportant artifacts.

提交回复
热议问题