Python CSV Writer trimming leading zeros

I am reading in a csv file in python, changing a few values, and writing it back out. I read in the file using:

bomReader = csv.reader( open( args.filename, 'rb' ), delimiter=',' )
for row in bomReader:
    #do stuff

One of the fields contains values such as 0406 , where the leading zero is important. After reading the csv file, if I print this field using say print row[2] , it displays correctly with the leading 0.

When I write this back in to my new csv file however, the output has no leading zero. I assume this is because it is considered to be an int and the leading zero is trimmed. As I can't use format specifiers in the csv.writer writeRow() function, what is the correct way to prevent this behaviour?

Code:

bomReader = csv.reader( open( args.filename, 'rb' ), delimiter=',' )
bomWriter = csv.writer(open(outfile, 'wb'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)

for row in bomReader:
try:
    qty = int(row[3])
    if (qty > 0):
        cs = row[4].split(';')
        for each in cs:
            bomWriter.writerow([row[0],row[1], row[2],'1',each.strip(),row[5],row[6],row[7],row[8],row[9]])
    elif (qty == 0):
        print "Deleted line"
    else:
        bomWriter.writerow(row)
except ValueError:
        bomWriter.writerow(row)

Sample row from the input csv file:

1007,C,0406,2,C456;C219,ANY,,,,,,

Rows in output csv file:

1007,C,406,1,C456,ANY,,,,
1007,C,406,1,C219,ANY,,,,

The codes you supplied are working correctly as you want under Python 2.6.7 and Python 2.7.2 , csv.__version=='1.0' . Output:

1007,C,0406,1,C456,ANY,,,,
1007,C,0406,1,C219,ANY,,,,
链接地址: http://www.djcxy.com/p/55088.html

上一篇: 避免使用csv.writer引用字符串数据行

下一篇: Python CSV编写器修剪前导零