[英]Adding a column in csv using python
I have hundreds of .csv files with 40 rows and 34 columns each. 我有数百个.csv文件,每个文件有40行和34列。 I want to add a column at position 26 and column 26-34 should shift to make space for the new one. 我想在位置26添加一列,而列26-34应该移动以为新列腾出空间。 First row of the file is empty and second row has the titles and rest have the values. 文件的第一行为空,第二行为标题,其余为值。 The new column should have a title in row two and rest of the rows can be zero. 新列应在第二行中具有标题,其余行可以为零。 Please help me with this code in python. 请帮我用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)
Inserting into a python list is pretty easy: some_list[2:2] = ['stuff','to','insert']
插入python列表非常简单: some_list[2:2] = ['stuff','to','insert']
So your code would look like the following: 因此您的代码如下所示:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.