Skip to content

Instantly share code, notes, and snippets.

@longlostnick
Last active August 23, 2021 07:52
Show Gist options
  • Save longlostnick/f9cae5a568656897041e to your computer and use it in GitHub Desktop.
Save longlostnick/f9cae5a568656897041e to your computer and use it in GitHub Desktop.
Read, transform, and write a csv file
Title Release Date Director
And Now For Something Completely Different 1971 Ian MacNaughton
Monty Python And The Holy Grail 1975 Terry Gilliam and Terry Jones
Monty Python's Life Of Brian 1979 Terry Jones
Monty Python Live At The Hollywood Bowl 1982 Terry Hughes
Monty Python's The Meaning Of Life 1983 Terry Jones
import csv
data = []
def transform_row(row):
title = line[0]
release_date = int(line[1])
director = line[2]
return [
# column 1
title,
# column 2: subtract 1000 from the year
release_date - 1000,
# column 4: empty column
None,
# column 3
director
]
# read csv file line by line
with open('input.csv', 'rb') as f:
reader = csv.reader(f)
# pop header row (1st row in csv)
header = reader.next()
# loop through each line in csv and transform
for line in reader:
# if the line is blank, skip this and keep going
if not line: continue
data.append(transform_row(line))
# write a new csv file
with open('output.csv', 'w') as f:
# define new csv writer
writer = csv.writer(f, delimiter=',')
# write a header row to our output.csv file
writer.writerow([
'Title',
'Date minus 1000',
None,
'Director'
])
# write our data to the file
writer.writerows(data)
@ZenMaxe
Copy link

ZenMaxe commented Aug 23, 2021

Thanks for Learn CSV

i love this example

you helped me bro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment