注意数据的类型,否则保存会有错误,比如long类型后面带L,需要将其去掉。
#coding=utf-8
#用于转换ip地址为填写空白处的函数
def ip2long(ip_string):
return ip_string.find('.') != -1 and reduce(lambda a, b: a << 8 | b, map(int, ip_string.split("."))) or ip_string
#定义打开的原始文件和需要保存的文件
old_file = open("E:\\testdata")
new_file = file("E:\\resultdata","a+")
###按行读取数据
for line in old_file:
a = line.split("\t")
newid = a[0]
start_ip = a[1]
end_ip = a[2]
start_num = a[3]
end_num = a[4]
city = a[5]
if newid >= 118675:
start_num = ip2long(start_ip.strip())
end_num = ip2long(end_ip.strip())
new_file.write("%s|%s|%s|%s|%s|%s\n"%(newid,start_ip,end_ip,str(start_num),str(end_num),city))
else:
new_file.write("%s|%s|%s|%s|%s|%s\n" % (newid, start_ip, end_ip, str(start_num), str(end_num), city))
#关闭文件
old_file.close()
new_file.close()