Home >Backend Development >Python Tutorial >How to Add a New Column to a CSV File Preserving Existing Values?
Adding a New Column to a CSV File
This article addresses the issue of adding a new column to multiple CSV files, existing in a format with two existing columns labeled "Name" and "Code." The desired output is to add a third column named "Berry" and populate its values with the "Name" values.
An initial Python script using the csv library attempted to append a 'Berry' value to each row, but encountered an error where only the new column was populated with 'Berry' values.
The Solution
The recommended code presented in the answer section provides a comprehensive solution:
Implementation
Here's a revised and improved Python script based on the provided solution:
<code class="python">import csv with open('input.csv', 'r') as infile, open('output.csv', 'w') as outfile: reader = csv.reader(infile) header = next(reader) header.append('Berry') writer = csv.writer(outfile) writer.writerow(header) for row in reader: row.append(row[0]) writer.writerow(row)</code>
This script successfully appends the new "Berry" column to each row, populated with the corresponding "Name" values.
Additional Considerations
The with statement can be used on multiple files in one line, as shown in the following example:
<code class="python">with open('input.csv', 'r') as infile, open('output.csv', 'w') as outfile: # file operations</code>
The above is the detailed content of How to Add a New Column to a CSV File Preserving Existing Values?. For more information, please follow other related articles on the PHP Chinese website!