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:
-
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. -
Create a
csv.writerobject: Use thecsv.writer()function to create a writer object that provides CSV writing functionality. -
Write data: Use the
writerow()method of the writer to write a single row, andwriterows()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']:
pythonimport 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
encodingparameter in theopen()function, such asencoding='utf-8'.
This implementation is straightforward and applicable to various data appending scenarios, making it highly practical for real-world applications.