如何替换csv文件特定单元格中的值?

2024-10-02 16:22:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想制作一个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]

文件如下所示:

^{pr2}$

在这个例子中,我需要用一个新值(newCTLcount)替换8696(在第2行单元格6上)。在


Tags: 文件csvcsvfile代码脚本aswithcounter
2条回答

明白了。。。在

 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]))

谢谢

最有可能的是,在阅读/解析的同时写作以节省内存

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)

对于python2,请参见https://docs.python.org/2/library/csv.html

相关问题 更多 >