0

I've been tasked with making a program that uses information from a CSV file and extracts the year a student joined the school, the first three letters of the first name and the first two letters of the surname.

This is my current code:

names = []                                                               
with open('Spreadsheet2.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        names.append(row)                                        
print(names)

Sample Output would be:

`[['John', 'Doe', '2018'], ['Edward', 'Kaizak', '2014'], 
 ['Elizabeth', 'Dezir', '2013'], ['Jack', 'Wilder', '2014'], 
 ['Lily', 'Rais', '2015'], ['Ken', 'Lowley', '2015'], 
 ['Edna', 'Bores', '2015'], ['Jacqueline', 'Keis', '2016'], 
 ['Tammy', 'Howst', '2017']]`

I need to write the extracted data to a new CSV file.

Any help is appreciated.

Dominique
  • 16,450
  • 15
  • 56
  • 112

2 Answers2

0

Here it is

import csv

new_rows = []
with open('in1.csv', 'r') as f_in:
    reader = csv.reader(f_in, delimiter=',')
    for row in reader:
        new_rows.append([row[0][:3], row[1][:2], row[2]])
    with open('out.csv', 'w',newline='') as f_out:
        writer = csv.writer(f_out, delimiter=',')
        writer.writerows(new_rows)

Input file:

John,Doe,2018
Jack,Smith,2017

Output file:

Joh,Do,2018
Jac,Sm,2017
balderman
  • 22,927
  • 7
  • 34
  • 52
  • Thank you for your help. What would you recommend I do to learn python better? – a_dulblade Mar 21 '19 at 14:22
  • Define small tasks (like that one you did with the csv) and work on the implementation. Use this website only after you did a serious effort to implement the task. – balderman Mar 21 '19 at 14:31
0

If your problem is generating the data, you should have a look at python's indexing operator.

  • Strings are just a list of characters
  • python has some really neat operator for selecting stuff in lists:
my_string = "hello there"

# first 3 characters
my_string[:3] # 'hel'

# last 5 characters
my_string[-5:] # 'there'

# from 3rd to 5th characters
my_string[3:5] # 'lo'

# last character
my_string[-1] # 'e'

# etc...

Cheers!

bastien girschig
  • 663
  • 6
  • 26