在python中的csv的一行中插入两个值

在python中的csv的一行中插入两个值,python,Python,原始csv: Identification O of O APC2 O 我的代码: def add_column_in_csv(input_file, output_file, transform_row): """ Append a column in existing csv using csv.reader / csv.writer classes""" # Open the input_fil

原始csv:

Identification  O
of      O
APC2    O
我的代码:

def add_column_in_csv(input_file, output_file, transform_row):
    """ Append a column in existing csv using csv.reader / csv.writer classes"""
    # Open the input_file in read mode and output_file in write mode
    with open(input_file, 'r') as read_obj, open(output_file, 'w', newline='') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj, delimiter='\t', quotechar='|')
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj, delimiter='\t', quoting=csv.QUOTE_NONE, escapechar='')
        # Read each row of the input csv file as list
        for row in csv_reader:
            
            # Pass the list / row in the transform function to add column text for this row
            transform_row(row)
            # Write the updated row / list to the output file
            csv_writer.writerow(row)

add_column_in_csv(ncbi_path + '/train_dev.tsv', ncbi_path + '/train_dev.csv', lambda row \
                  : row.insert(1, 'NN'+'\t'+ 'NN'))
结果:

Identification  ['NN', 'NN']    O
of      ['NN', 'NN']    O
APC2    ['NN', 'NN']    O
预期:

Identification  NN  NN    O
of      NN  NN   O
APC2    NN  NN    O
把你的lambda换成

lambda row : row[:1]+['NN', 'NN']+row[1:]
并转化为

row = transform_row(row)