Python:替换csv的某些行但不替换其他行

时间:2018-02-07 01:34:07

标签: python csv

我正在尝试从原始文件创建一个新的csv文件。新的csv文件应该是旧的副本,但一列中的一系列值乘以常量除外。要改变的值从行i到j包含。这是我正在尝试的代码:

import csv
import itertools

i, j = 2, 10785

infile = open('../../combined_kW.csv', 'r')
outfile = open('../../combined_kW_adj.csv', 'w')
reader = csv.reader(infile, delimiter= ',')
datawriter = csv.writer(outfile, delimiter=',')

datawriter.writerow(['date', 'PVkW', 'TBLkW'])
next(reader)    # there is a header row

for row in reader:
    for row in itertools.islice(reader, i, j):
        row[1] = row[1].replace(row[1], str(float(row[1]) * 5))
    datawriter.writerow((row[0], row[1], row[2]))

从大约25,000行的csv中,返回文件的内容仅为:

date,PVkW,TBLkW
2016/04/04 03:00,0.0,207.23748999999998
2017/07/19 09:00,2921.5,287.15625
2018/01/12 18:00,0.0,267.9414

其中没有一个与上面指定的行i和j有关。我怎么能更好地解决这个问题?

1 个答案:

答案 0 :(得分:1)

import csv

i, j = 2, 10785

# assuming Python 3; otherwise omit 'newline'
with open('../../combined_kW.csv', 'r', newline='') as f:
    r = csv.reader(f, delimiter=',')
    rows = list(r)

# slice creates a shallow copy
# meaning each element still points to the same array element in rows!
for row in rows[i:j]:
    row[1] = row[1].replace(row[1], str(float(row[1]) * 5))

with open('../../combined_kW_adj.csv', 'w', newline='') as f:
    w = csv.writer(f, delimiter=',')
    w.writerows(rows)