首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

用于将行从一个CSV复制到另一个CSV并添加列的Python代码

以下是用于将行从一个CSV复制到另一个CSV并添加列的Python代码:

代码语言:txt
复制
import csv

def copy_csv_with_column(source_file, destination_file, column_name, column_value):
    with open(source_file, 'r') as source_csv, open(destination_file, 'w', newline='') as dest_csv:
        reader = csv.reader(source_csv)
        writer = csv.writer(dest_csv)
        
        # Read the header row from the source CSV
        header = next(reader)
        
        # Add the new column to the header
        header.append(column_name)
        
        # Write the modified header to the destination CSV
        writer.writerow(header)
        
        # Iterate over the rows in the source CSV
        for row in reader:
            # Add the column value to each row
            row.append(column_value)
            
            # Write the modified row to the destination CSV
            writer.writerow(row)

# Example usage
copy_csv_with_column('source.csv', 'destination.csv', 'New Column', 'Value')

这段代码使用Python的csv模块实现了将行从一个CSV文件复制到另一个CSV文件并添加列的功能。具体步骤如下:

  1. 打开源CSV文件和目标CSV文件。
  2. 创建CSV读取器和写入器。
  3. 读取源CSV文件的头部行,并将新列名添加到头部行。
  4. 将修改后的头部行写入目标CSV文件。
  5. 遍历源CSV文件中的每一行。
  6. 将新列值添加到每一行。
  7. 将修改后的行写入目标CSV文件。

这段代码可以用于将一个CSV文件的数据复制到另一个CSV文件,并在目标文件中添加一个新的列。你可以根据实际需求修改源CSV文件的路径、目标CSV文件的路径、新列的名称和值。

腾讯云相关产品和产品介绍链接地址:

请注意,以上链接仅供参考,具体产品选择应根据实际需求和情况进行评估。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券