python: 如果我的值少于三位则添加零
我有一个csv文件,如果里面的数字少于4位,就需要在前面加一个零。
我只需要更新特定的一行:
import csv
f = open('csvpatpos.csv')
csv_f = csv.reader(f)
for row in csv_f:
print row[5]
然后我想逐个查看这一行的数字,把那些少于4位的数字前面加个0。最后,把这些调整过的数据放到一个新的csv文件里。
4 个回答
0
给你两个小提示:
s = "486"
s.isdigit() == True
用来找出哪些东西是数字。
还有
s = "486"
s.zfill(4) == "0486"
用来填充零。
2
当你想到解析数据的时候,通常会想到 正则表达式 或者 pyparsing。在这个例子中,使用 正则表达式
来解析数据会非常简单。
但这还不是全部,一旦你能解析出数字,你还需要进行零填充。为此,你需要使用 str.format 来调整和填充字符串。
考虑一下你的字符串
st = "parse through that row and add a 0 to the front of any number that is shorter than 4 digits."
在上面的代码中,你可以做一些类似的事情
实现
parts = re.split(r"(\d{0,3})", st)
''.join("{:>04}".format(elem) if elem.isdigit() else elem for elem in parts)
输出
'parse through that row and add a 0000 to the front of any number that is shorter than 0004 digits.'
3
1
下面的代码会读取指定的 csv
文件,逐行遍历每一行和每一行中的每个项目,然后把这些内容输出到一个新的 csv
文件中。
import csv
import os
f = open('csvpatpos.csv')
# open temp .csv file for output
out = open('csvtemp.csv','w')
csv_f = csv.reader(f)
for row in csv_f:
# create a temporary list for this row
temp_row = []
# iterate through all of the items in the row
for item in row:
# add the zero filled value of each temporary item to the list
temp_row.append(item.zfill(4))
# join the current temporary list with commas and write it to the out file
out.write(','.join(temp_row) + '\n')
out.close()
f.close()
你的结果会保存在 csvtemp.csv
文件里。如果你想用原来的文件名保存数据,只需在脚本的最后加上以下代码。
# remove original file
os.remove('csvpatpos.csv')
# rename temp file to original file name
os.rename('csvtemp.csv','csvpatpos.csv')
更符合Python风格的版本
上面的代码写得比较详细,以便让人理解。这里是经过改进的代码,更加 符合Python风格。
import csv
new_rows = []
with open('csvpatpos.csv','r') as f:
csv_f = csv.reader(f)
for row in csv_f:
row = [ x.zfill(4) for x in row ]
new_rows.append(row)
with open('csvpatpos.csv','wb') as f:
csv_f = csv.writer(f)
csv_f.writerows(new_rows)