Home >Backend Development >Python Tutorial >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:
Obtain and Modify Headers:
Iterate and Modify Remaining Rows:
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!