Home  >  Article  >  Backend Development  >  How to Add a New Column to a CSV File Preserving Existing Values?

How to Add a New Column to a CSV File Preserving Existing Values?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-21 21:12:02302browse

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:

  • Read the first row from the input CSV file and append the header 'berry' to it.
  • Iterate through the remaining lines and append the first value (the name) to each row.
  • Write all modified rows to the output CSV file.

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

  • Be aware that the default line terminator in Python's csv library is 'rn,' which may cause double spacing in output files. To specify a different line terminator, use the lineterminator parameter during CSV file writing.
  • Consider using a list to store all the modified rows and write them in one operation with writerows. This approach can be more efficient for large files.
  • 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn