ean13码的生成,python读取csv中数据并处理返回并写入到另一个csv文件中

# -*- coding: utf-8 -*-
import math
import re
import csv
import repr
def ean_checksum(eancode):
    """returns the checksum of an ean string of length 13, returns -1 if the string has the wrong length"""
    if len(eancode) != 13:
        return -1
    oddsum=0
    evensum=0
    total=0
    eanvalue=eancode
    reversevalue = eanvalue[::-1]
    finalean=reversevalue[1:]

    for i in range(len(finalean)):
        if i % 2 == 0:
            oddsum += int(finalean[i])
        else:
            evensum += int(finalean[i])
    total=(oddsum * 3) + evensum

    check = int(10 - math.ceil(total % 10.0)) %10
    return check

def sanitize_ean13(csvfile):
    reader = csv.reader(file(csvfile,'rb'))
    writer = csv.writer(file('C:/Users/Administrator/Desktop/1.csv','wb'))
    for id,ean13 in reader:
        if not ean13:
            return "0000000000000"
        ean13 = str(ean13)
        ean13 = '0' * (9-len(ean13)) + ean13
        ean13 = '042' + ean13
        ean13 = re.sub("[A-Za-z]","0",ean13);
        ean13 = re.sub("[^0-9]","",ean13);
        ean13 = ean13[:13]
        if len(ean13) < 13:
            ean13 = ean13 + '0' * (13-len(ean13))
        s=ean13[:-1] + str(ean_checksum(ean13))
        writer.writerow([id,s])
sanitize_ean13('C:/Users/Administrator/Desktop/res.partner.csv')

 

posted @ 2016-05-24 23:29  屌丝IT男  阅读(2822)  评论(0编辑  收藏  举报