@堆栈溢出
我有一个脚本,它根据匹配的 3 个条件将三列添加到我的 csv 末尾。
我理解这个问题,代码是从 rdr 重新读取行,而 wrt 是修改后的行,在初始循环之后我尝试遍历 wrt,但代码无法做到这一点。
我的代码:
import csv
import datetime
import copy
from collections import defaultdict
with open(r"FullMergedData.csv") as i, open(r"FullMergedDataWSPSR.csv", "wb") as o:
rdr = csv.reader(i, delimiter ="|")
wrt = csv.writer(o, delimiter ="|")
data, currdate = defaultdict(lambda:[0, 0, 0, 0]), None
calclist = [6, 7, 19, 23, 25, 26, 35, 62, 64]
for calc in calclist:
for counter2, line in enumerate(rdr):
if counter2 != 0:
date, name = datetime.datetime.strptime(line[50], '%d/%m/%Y'), line[calc]
if date != currdate or not currdate:
for v in data.itervalues():
v[:2] = v[2:]
currdate = date
top,bottom = data[name][0:2]
try:
quotient = float(top)/bottom
except ZeroDivisionError:
quotient = 0
wrt.writerow(line + data[name][:2]+ [quotient])
data[name][3] += 1
if line[38] == "1": data[name][2] += 1
如果有人可以帮助使此代码正常工作,我将不胜感激。非常感谢 AEA
产生回溯的代码
import csv
import datetime
import copy
from collections import defaultdict
with open(r"FullMergedData.csv") as i, open(r"FullMergedDataWSPSR.csv", "wb") as o:
rdr = csv.reader(i, delimiter ="|")
wrt = csv.writer(o, delimiter ="|")
data, currdate = defaultdict(lambda:[0, 0, 0, 0]), None
calclist = [6, 7, 19, 23, 25, 26, 35, 62, 64]
for counter, calc in enumerate(calclist):
if counter == 0:
for counter2, line in enumerate(rdr):
if counter2 != 0:
date, name = datetime.datetime.strptime(line[50], '%d/%m/%Y'), line[calc]
if date != currdate or not currdate:
for v in data.itervalues():
v[:2] = v[2:]
currdate = date
top,bottom = data[name][0:2]
try:
quotient = float(top)/bottom
except ZeroDivisionError:
quotient = 0
wrt.writerow(line + data[name][:2]+ [quotient])
data[name][3] += 1
if line[38] == "1": data[name][2] += 1
else:
for line in wrt:
date, name = datetime.datetime.strptime(line[50], '%d/%m/%Y'), line[calc]
if date != currdate or not currdate:
for v in data.itervalues():
v[:2] = v[2:]
currdate = date
top,bottom = data[name][0:2]
try:
quotient = float(top)/bottom
except ZeroDivisionError:
quotient = 0
wrt.writerow(line + data[name][:2]+ [quotient])
data[name][3] += 1
if line[38] == "1": data[name][2] += 1
追溯
Traceback (most recent call last):
File "C:\mergecalculator.py", line 35, in <module>
for line in wrt:
TypeError: '_csv.writer' object is not iterable