Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created September 30, 2023 01:47
Show Gist options
  • Save code-boxx/c56fd961f470387f60107285128463d0 to your computer and use it in GitHub Desktop.
Save code-boxx/c56fd961f470387f60107285128463d0 to your computer and use it in GitHub Desktop.
Python Append Prepend Insert Row Into CSV

PYTHON CSV ADD NEW ROWS

https://code-boxx.com/python-add-rows-csv/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# (A) LOAD CSV MODULE
import csv
# (B) OPEN CSV & APPEND ROWS
with open("demo.csv", "a", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["A", "B"])
writer.writerows([["C", "D"], ["E", "F"]])
# (A) LOAD CSV MODULE
import csv
# (B) READ EXISTING ROWS INTO A LIST
with open("demo.csv", "r", newline="") as csvfile:
rows = list(csv.reader(csvfile))
# (C) PREPEND NEW ROWS
rows = [["G", "H"], ["I", "J"]] + rows
# (D) SAVE UPDATED CSV
with open("demo.csv", "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerows(rows)
# (A) LOAD CSV MODULE
import csv
# (B) READ EXISTING ROWS INTO A LIST
with open("demo.csv", "r", newline="") as csvfile:
rows = list(csv.reader(csvfile))
# (C) INSERT ROWS
rows.insert(3, ["K", "L"])
# (D) SAVE UPDATED CSV
with open("demo.csv", "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerows(rows)
# (A) LOAD CSV MODULE
import csv
# (B) READ EXISTING ROWS INTO A LIST
with open("demo.csv", "r", newline="") as csvfile:
rows = list(csv.reader(csvfile))
# (C) INSERT BEFORE "JON DOE"
at = 0
for i, r in enumerate(rows):
if "Jon Doe" in r:
at = i
break
# (D) INSERT NEW ROWS
rows.insert(at, ["M", "N"])
# (E) SAVE UPDATED CSV
with open("demo.csv", "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerows(rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment