Home  >  Article  >  Backend Development  >  How to Append a New Column to Multiple CSV Files and Align Entries with Corresponding Rows Using Python?

How to Append a New Column to Multiple CSV Files and Align Entries with Corresponding Rows Using Python?

DDD
DDDOriginal
2024-10-21 21:02:02593browse

How to Append a New Column to Multiple CSV Files and Align Entries with Corresponding Rows Using Python?

Appending a New Column to CSV Files

Initial Question:

Users desire to add a new column named "Berry" to multiple CSV files, aligning the entries with corresponding rows. The current Python script, however, skips lines and assigns only "Berry" to the new column.

Solution:

  1. Obtain and Modify Headers:

    • Retrieve the first row (headers) using next() (Python 3):
    • Append the "Berry" header to indicate the new column.
  2. Iterate and Modify Remaining Rows:

    • Loop through the remaining CSV lines using a reader object.
    • For each line, append the first column's value to the new "Berry" column.

Below is the modified Python script incorporating these changes:

<code class="python">import csv

with open('input.csv', 'r') as csvinput, open('output.csv', 'w', newline='') as csvoutput:
    writer = csv.writer(csvoutput)
    reader = csv.reader(csvinput)

    headers = next(reader)
    headers.append('Berry')
    writer.writerow(headers)

    for row in reader:
        row.append(row[0])
        writer.writerow(row)</code>

The above is the detailed content of How to Append a New Column to Multiple CSV Files and Align Entries with Corresponding Rows Using Python?. 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