我有数百个.csv文件,每行40行34列。我想在第26位添加一列,第26-34列应该移位以为新的列腾出空间。该文件的第一行为空,第二行具有标题,其余的具有值。新列应在第二行中具有标题,其余行可以为零。 请帮我在python中使用这段代码。
import csv
infilename = r'C:\Users\Sulabh Kumra\Desktop\input.csv'
outfilename = r'C:\Users\Sulabh Kumra\Desktop\output.csv'
with open(infilename, 'rb') as fp_in, open(outfilename, 'wb') as fp_out:
reader = csv.reader(fp_in, delimiter=",")
headers = next(reader) # read first row
writer = csv.writer(fp_out, delimiter=",")
writer.writerow(headers)
for row in reader:
row.append(row[2])
writer.writerow(row)
答案 0 :(得分:0)
插入python列表非常简单:some_list[2:2] = ['stuff','to','insert']
所以你的代码如下所示:
import csv
infilename = r'C:\Users\Sulabh Kumra\Desktop\input.csv'
outfilename = r'C:\Users\Sulabh Kumra\Desktop\output.csv'
with open(infilename, 'rb') as fp_in, open(outfilename, 'wb') as fp_out:
reader = csv.reader(fp_in, delimiter=",")
writer = csv.writer(fp_out, delimiter=",")
blank_line = next(reader)
writer.writerow(blank_line)
headers = next(reader) # read title row
headers[26:26] = ['New Label']
writer.writerow(headers)
for row in reader:
row[26:26] = [0]
writer.writerow(row)