[英]csv writer pad with zeroes
I have a working python script that takes a .csv input, takes out the 4 columns that I want, trims all white space, and writes it to a new file. 我有一个工作的python脚本,它需要一个.csv输入,取出我想要的4列,修剪所有空白,并将其写入新文件。 There's only one thing I can't figure out how to do...
我只有一件事我不知道该怎么做...
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"
I need to modify the 3rd column, number
, either when the input file is being read, or when the output file is being written, so that each value is 9 digits long, padded with zeroes to the left. 我需要在读取输入文件或写入输出文件时修改第3列
number
,以使每个值的长度为9位,并在左侧填充零。 The input will never be greater than 9, so: 输入将永远不会大于9,因此:
Output: 输出:
Input | Output
1234 | 000001234
393939392 | 393939392
5 | 000000005
I'm not sure at all how I would go about this though. 我完全不确定该如何处理。 Any input would be appreciated!
任何输入将不胜感激!
You can conver integers to string first, and then use zfill
function. 您可以先将整数转换为字符串,然后再使用
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
Even if you have negative number, you can still use zfill()
to fill it. 即使您有负数,您仍然可以使用
zfill()
进行填充。
>>> print(str(-123).zfill(9))
-00000123
As already proposed in the comments, the following works on my machine: 正如评论中已经提出的,以下内容可以在我的机器上运行:
# ...
row['number'] = "{:09d}".format(int(row['number']))
w.writerow(row)
The simplest way would be to just use the zfill()
string method on the one field (no need to convert it into a integer first). 最简单的方法是只在一个字段上使用
zfill()
字符串方法(无需先将其转换为整数)。 You can also handle writing the header row in the output file by just calling the csv.DictWriter.writeheader()
method: 您还可以通过仅调用
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.