edit csv file in python

To edit a CSV file in Python, you can use the csv module. Here are the steps to edit a CSV file:

  1. Open the CSV file using the open() function with the appropriate file mode ('r' for read or 'w' for write).
  2. Create a csv.writer object by passing the opened file as a parameter.
  3. Use the writerow() method of the csv.writer object to write rows to the CSV file.
  4. Close the file using the close() method.

Here's an example that demonstrates how to edit a CSV file by appending a new row:

main.py
import csv

# Step 1: Open the CSV file in 'a' (append) mode
with open('data.csv', 'a', newline='') as file:

    # Step 2: Create a csv.writer object
    writer = csv.writer(file)

    # Step 3: Write a new row to the CSV file
    new_row = ['John', 'Doe', 'john@example.com']
    writer.writerow(new_row)

# Step 4: Close the file
file.close()
346 chars
15 lines

In this example, a new row with the values John, Doe, and john@example.com is appended to the existing CSV file named data.csv.

Please note that this example assumes that the CSV file already exists. If the file doesn't exist, you can create a new file by opening it in 'w' (write) mode instead of 'a' (append) mode.

Additionally, you can use other methods from the csv module to read and modify existing rows in the CSV file.

related categories

gistlibby LogSnag