我想创建一个python脚本,它有一个计数器,用于替换CSV文件中特定单元格的当前值。
我的代码是:
with open(ctlLst[-1], 'rb') as csvfile:
csvReader = csv.reader(csvfile)
csvReader.next()
for row in csvReader:
if row[6]>counter:
newCTLcount=int(row[6])-counter
#need to replace cell row[6]
该文件如下所示:
InterfaceCode InterfaceSeqID OperatorCode CreationDateTime MintransactionDateTime MaxtransactionDateTime NoOfRows ControlFileName DataFileName
201 1170 30 20161005 04:30:27 20161004 06:55:56 20161005 03:08:37 8696 CTL_TripEventAndAlert_30_20161004.CSV TripEventAndAlert_30_20161004.CSV
在这个例子中,我需要用新值(newCTLcount)替换8696(第2行单元格6)的值。
答案 0 :(得分:0)
最有可能的做法是在阅读/解析时编写以节省内存
with open('out.csv', 'wb') as outfile:
with open(ctlLst[-1], 'rb') as csvfile:
csvReader = csv.reader(csvfile)
csvWriter = csv.writer(outfile)
csvReader.next()
for row in csvReader:
row[6] = int(row[6]) # assumed as int
if row[6] > counter:
row[6] -= counter
outfile.writerow(row)
对于Python 2,请参阅https://docs.python.org/2/library/csv.html
答案 1 :(得分:0)
得到它......
rowData=[]
with open(ctlLst[-1], 'rb') as csvfile:
csvReader = csv.reader(csvfile)
for row in csvReader:
rowData.append(row)
rowData[1][6]=int(rowData[1][6])-counter
print ("new Row data count is " + str(rowData[1][6]))
谢谢