How to append a new row to an old CSV file in Python?

1个答案

1
最佳答案

In Python, appending new rows to an existing CSV file can typically be achieved using the csv module from the standard library. The specific steps and code example are as follows:

  1. Open the file: Use the open() function to open the file with the mode 'a' (append), which allows appending data to the end of the file without overwriting existing content.

  2. Create a csv.writer object: Use the csv.writer() function to create a writer object that provides CSV writing functionality.

  3. Write data: Use the writerow() method of the writer to write a single row, and writerows() to write multiple rows.

Here is a specific example. Suppose we have a file named data.csv, and we want to append a row of data, such as ['John', 28, 'Engineer']:

python
import csv # Define the data to append new_data = ['John', 28, 'Engineer'] # Open the file in append mode with open('data.csv', 'a', newline='') as file: writer = csv.writer(file) # Write a single row of data writer.writerow(new_data) print("Data appended successfully.")

This code appends a row containing John, 28, Engineer to the end of data.csv. If the file does not exist, the open() function will create a new file.

Notes:

  • Ensure that newline='' is used when opening the file to avoid inconsistencies in newline characters across different operating systems.
  • When handling Chinese or other non-ASCII characters, it is recommended to specify the encoding parameter in the open() function, such as encoding='utf-8'.

This implementation is straightforward and applicable to various data appending scenarios, making it highly practical for real-world applications.

2024年7月20日 14:47 回复

你的答案