To edit a CSV file in Python, you can use the csv
module. Here are the steps to edit a CSV file:
open()
function with the appropriate file mode ('r'
for read or 'w'
for write).csv.writer
object by passing the opened file as a parameter.writerow()
method of the csv.writer
object to write rows to the CSV file.close()
method.Here's an example that demonstrates how to edit a CSV file by appending a new row:
main.py346 chars15 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.
gistlibby LogSnag