如何在python中的csv文件的起始位置添加列



我有一个python程序,可以将csv文件转换为'^'分隔符文件。输出文件也有新的头。

cc = input("Enter Code t")
cn = input("Enter Item Number t")
input_file = input("Enter input file t")
act = input("Enter Action (Update- N/Delete -Y) t")
def file_conversion(input_file, output_file_pattern, chunksize):
with open(input_file,"r+") as fin:
# ignore headers of input files
for i in range(1):
fin.__next__()
reader = csv.reader(fin, delimiter=',')
for i, chunk in enumerate(chunked(reader, chunksize)):
with open(output_file_pattern.format(i), 'w', newline='') as fout:
writer = csv.writer(fout,reader,delimiter='^')
writer.writerow(headers)
writer.writerows(chunk)
print("Successfully converted into", output_file_pattern)

程序现在工作了,我想在每一行输出分隔符文件中添加act、cc和cn。输出文件的行应该像下面的行一样开始

act^cc^cn^restofcsvdelimitierfiles. 

这解决了我的问题

def add_column_in_csv(input_file, output_file, transform_row,transform_row1,transform_row2):
with open(input_file, 'r') as read_obj:
with open(output_file, 'w', newline='') as write_obj:
reader = csv.reader(read_obj,delimiter=',')
writer = csv.writer(write_obj)
for row in reader:
transform_row(row,reader.line_num)
transform_row1(row,reader.line_num)
transform_row2(row,reader.line_num)
writer.writerow(row)
add_column_in_csv(path0,path1, lambda row, line_num: row.insert(0, act),lambda row, line_num: row.insert(1,cc),lambda row, line_num: row.insert(2,cn))

相关内容

  • 没有找到相关文章

最新更新