csv写作垫用零

时间:2016-07-14 16:31:38

标签: python csv

我有一个工作的python脚本,它接受.csv输入,取出我想要的4列,修剪所有空格,并将其写入新文件。只有一件事我无法弄明白该怎么做......

<span style="cursor:pointer" onclick="toggleNav();">...</span>

我需要修改第3列import csv,time,string,os,requests dw = "\\\\network\\folder\\btc.csv" inv_fields = ["id", "rsl", "number", "color_b4"] with open(dw) as infile, open("c:\\upload\\log.csv", "wb") as outfile: r = csv.DictReader(infile) w = csv.DictWriter(outfile, inv_fields, extrasaction="ignore") r = (dict((k, v.strip()) for k, v in row.items() if v) for row in r) wtr = csv.writer( outfile ) wtr.writerow(["id", "resale", "number", "favorite_color"]) for i, row in enumerate(r, start=1): row['id'] = i w.writerow(row) print "file successfully saved" ,或者在读取输入文件时,或者在写入输出文件时,以便每个值都是9位长,用左边的零填充。输入永远不会大于9,所以:

输出:

number

我完全不确定如何解决这个问题。任何意见都将不胜感激!

3 个答案:

答案 0 :(得分:1)

您可以先将整数转换为字符串,然后使用zfill函数。

>> print str(123).zfill(9)
000000123
>> print str(123).zfill(2)
123
>> print str(123).zfill(3)
123
>> print str(123).zfill(4)
0123

即使您有负数,您仍然可以使用zfill()来填充它。

>>> print(str(-123).zfill(9))
-00000123

答案 1 :(得分:1)

正如评论中已经提出的,以下内容适用于我的机器:

# ...
row['number'] = "{:09d}".format(int(row['number']))
w.writerow(row)

答案 2 :(得分:1)

最简单的方法是在一个字段上使用zfill()字符串方法(不需要先将其转换为整数)。您还可以通过调用csv.DictWriter.writeheader()方法来处理输出文件中的标题行:

import csv,time,string,os,requests
dw = "\\\\network\\folder\\btc.csv"

inv_fields = ["id", "rsl", "number", "color_b4"]

with open(dw, 'rb') as infile, open("c:\\upload\\log.csv", "wb") as outfile:
    r = csv.DictReader(infile)
    w = csv.DictWriter(outfile, inv_fields, extrasaction="ignore")

    r = (dict((k, v.strip()) for k, v in row.items() if v) for row in r)

    w.writeheader()
    for i, row in enumerate(r, start=1):
        row['id'] = i
        row['number'] = row['number'].zfill(9)  # added
        w.writerow(row)

print "file successfully saved"