Skip to content

Instantly share code, notes, and snippets.

@garolpe
Created November 23, 2019 22:32
Show Gist options
  • Save garolpe/3da05d96a5e40ddd591d4449e9d780b1 to your computer and use it in GitHub Desktop.
Save garolpe/3da05d96a5e40ddd591d4449e9d780b1 to your computer and use it in GitHub Desktop.
Add header to every row in CSV file
#Copyright 2019 garol.net
#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.
'''
I wrote this because i need to add header to every row in excel file and have
it followed by single blank row.
In pure excel this is hard to achieve without manual construction of it.
ATTENTION: I use specific encoding!!!! UTF-8
If you are not using utf-8 remove it from code... And be careful!
Excel during saving as CSV UTF-8 do not use pure UTF-8!
If some problem happend - can be caused by encoding :)
'''
#placeholder for original and new csv file
original = []
new = []
#read lines from original file
with open('csv_zoznam.csv', encoding='utf-8') as f:
for line in f:
original.append(line)
#create header to replicate
header = original[0]
#remove it from original and keep what "remain"
remain = original[1:]
#construct new file structure and append header, line itself and blank row for
#every row in "remain"
for line in remain:
new.append(header)
new.append(line)
new.append(";;;\n")
#write it to new file
with open('csv_new.csv', mode='w', encoding='utf-8') as f:
for line in new:
f.write(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment