Last active
September 6, 2019 11:56
-
-
Save mhamilt/c2a582ca085950b791bdb8a73f4a8971 to your computer and use it in GitHub Desktop.
add a column to a csv file with some robust handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv, os | |
def add_csv_column(filename: str, column_name: str, data: list) -> None: | |
""" | |
Add a column of data to an existing csv file | |
pads with empty string if data size does not match target csv | |
:param filename: path to csv file | |
:param column_name: name of new column | |
:param data: list of data | |
""" | |
path, file = os.path.split(filename) | |
tempfile = os.path.join(path, '~' + file) | |
with open(filename, 'r') as csvinput, open(tempfile, 'w') as csvoutput: | |
writer = csv.writer(csvoutput, lineterminator='\n') | |
reader = csv.reader(csvinput) | |
all = [] | |
row = next(reader) | |
row.append(column_name) | |
all.append(row) | |
data.reverse() | |
number_of_cols = len(row[0]) | |
for row in reader: | |
row.append(data.pop() if data else '') | |
all.append(row) | |
while data: | |
all.append(([''] * number_of_cols) + [data.pop()]) | |
writer.writerows(all) | |
os.remove(filename) | |
os.rename(tempfile, filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment