SlideShare a Scribd company logo
Computer Science 151
An introduction to the art of computing
CSV writing
Rudy Martinez
CS151 Spring 2019
Notes on Homework 2a
1. Open file and pass to file object (myfile, open(file,r))
2. Call csv reader on file object and pass to variable (myfile)
3. Create global dictionary to hold values (DATA = {})
a. Key = date,
b. Value = [tmax, tmin]
4. Create counter for the number of records.
5. For every line in myfile variable
a. If counter == 0 then eat header
i. Increment counter
b. Else
i. If tmax is not empty AND tmin is not empty
1. Then write row to global dictionary (DATA)
2. Increment counter
ii. Else:
1. Increment counter (drop row from final list)
6. Open file and pass to file object (myNewFile, open(newfile, w))
7. For every row in dictionary {DATA) (for loop)
a. Write row to myNewFile object (csv.writerow)
CS151 Spring 2019
Writing Dictionary or List to CSV
This is just like writing a normal file.
#Create file object!
myNewFile = open(‘test1.csv’, ‘w’) # This will overwrite test1 each time it runs!
#Create variable to write to
writer = csv.writer(myNewFile)
#write each row in Data List/Dictionary to file
for row in DATA:
writer.writerow(row) # write a single row (as retrieved by for loop)
Output:
['1994-04-01', '74', '35']
['1994-04-02', '68', '38']
['1994-04-04', '70', '']
CS151 Spring 2019
Writing Dictionary or List to CSV
This is an alternate way of writing to a csv file.
#Create file object!
myNewFile = open(‘test2.csv’, ‘w’) # This will overwrite test1 each time it runs!
#Create variable to write to
writer = csv.writer(myNewFile)
#write each row in Data List/Dictionary to file
writer.writerows(DATA) # write all rows at once!
Output:
['1994-04-01', '74', '35']
['1994-04-02', '68', '38']
['1994-04-04', '70', '']
CS151 Spring 2019
Paths on Linux and Windows
● Paths are basically the same for Linux and Mac!
● Linux =(‘/home/[username]/Documents/myfile.txt’)
● Windows =(r ‘C:Users[username]Documentsmyfile.txt’)
○ Must add ‘r’ to the command for it to read the backslash
● Linux doesn’t need to be told what drive (C: on windows)
● Windows uses a backslash (‘’) and Linux/Mac use a forward slash (‘/’)
Notes for Linux/Mac: if you see a tilde (‘~’) that usually means home folder:
‘~/Documents’ == ‘/home/bob/Documents’
CS151 Spring 2019
Summation Exercise
DATA = [‘1’,’1’,’1’,’1’]
summation = 0
for row in DATA:
summation += int(row[0])
print(str(sumation))
Output:
4
* A note your CSV files are all strings!
CS151 Spring 2019
Summation Example 2
# New list with 5 elements of type int
DATA2 = [1,1,1,1,1]
# Initialize sum variable to 0
summation1 = 0
# can use sum function from python!
summation1 = sum(DATA2)
# Print result
print(summation1)
Output:
5
CS151 Spring 2019
There is a difference!
DATA = [‘1’,’1’,’1’,’1’]
DATA2 = [1,1,1,1,1]
These are two completely different lists
DATA == strings
DATA2 == ints
!Sum only works on list of ints, or floats!
CS151 Spring 2019
Conversions
● Convert from string to int
○ int(‘1’) -> 1
● Convert from int to string
○ str(1) -> ‘1’
● Convert from string to datetime object!
from datetime import datetime
from datetime import date
myString = ‘1994-04-01’
myDateVar2 = datetime.strptime(myString, '%Y-%m-%d').date()
myString myDateVar2.year myDateVar2.month
myDateVar2.day
‘1994-04-01’ 1994 04
01
CS151 Spring 2019
Lets convert some lists
DATA3 = ['1','2','34','56']
# Now lets convert in place!
for counter in range(0, len(DATA3), 1):
# Grab string and convert to integer and store in variable
myInt = int(DATA3[counter])
# Copy back to list (remember it's mutable so we can do this)
DATA3[counter] = myInt
# Now I can just call sum on DATA3 since it's all int
print('Summation of whole list = ', str(sum(DATA3)))
print('Average of list items is = ', str(sum(DATA3)/len(DATA3)))
Output:
Summation of whole list = 93
Average of list items is = 23.25
CS151 Spring 2019
Let’s Review
● Write out what you need to do for the homework using the algorithm given.
○ Think about how to eat the elephant.

More Related Content

PDF
Billing Software By Harsh Mathur.
PPTX
Sorting
PPTX
Group functions
PPTX
Data structures Lecture no.6
PPTX
Lecture 1 mte 407
PPTX
Lecture 1 mte 407
DOC
PPTX
Programming in c
Billing Software By Harsh Mathur.
Sorting
Group functions
Data structures Lecture no.6
Lecture 1 mte 407
Lecture 1 mte 407
Programming in c

What's hot (20)

PDF
Joc live session
PDF
Algorithms: II
PPTX
Pa1 session 5
PPTX
hash
PPTX
Radix sort
PPT
16858 memory management2
PDF
CBSE Python List Assignment
PPTX
Address calculation-sort
PPTX
Implementation of queue using singly and doubly linked list.
PDF
Python List Comprehensions
DOCX
PPTX
Date & time functions in VB.NET
 
PPTX
Radix and shell sort
PDF
Algorithms: I
PPT
02 Arrays And Memory Mapping
PDF
Chunked, dplyr for large text files
PPTX
Getting started - Warewolf Syntax
PPTX
CS151 FIle Input and Output
DOC
Work flow
PDF
Stack & Queue
Joc live session
Algorithms: II
Pa1 session 5
hash
Radix sort
16858 memory management2
CBSE Python List Assignment
Address calculation-sort
Implementation of queue using singly and doubly linked list.
Python List Comprehensions
Date & time functions in VB.NET
 
Radix and shell sort
Algorithms: I
02 Arrays And Memory Mapping
Chunked, dplyr for large text files
Getting started - Warewolf Syntax
CS151 FIle Input and Output
Work flow
Stack & Queue
Ad

Similar to CS 151 CSV output (20)

PPTX
Cs 151 dictionary writer
PPTX
CS 151 homework2a
PPTX
CS151 Deep copy
PPTX
CS 151 Date time lecture
PDF
Lec04-CS110 Computational Engineering
PDF
Data import-cheatsheet
PDF
R_CheatSheet.pdf
PPTX
Unit I - 1R introduction to R program.pptx
PPT
Abapprogrammingoverview 090715081305-phpapp02
PPT
Chapter 1abapprogrammingoverview-091205081953-phpapp01
PPT
ABAP Programming Overview
PPT
chapter-1abapprogrammingoverview-091205081953-phpapp01
PPT
Chapter 1 Abap Programming Overview
PPT
Abapprogrammingoverview 090715081305-phpapp02
DOCX
Lab 3 Set Working Directory, Scatterplots and Introduction to.docx
PPT
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
PDF
Raspberry Pi - Lecture 5 Python for Raspberry Pi
PPT
List Processing in ABAP
PDF
Python Variable Types, List, Tuple, Dictionary
Cs 151 dictionary writer
CS 151 homework2a
CS151 Deep copy
CS 151 Date time lecture
Lec04-CS110 Computational Engineering
Data import-cheatsheet
R_CheatSheet.pdf
Unit I - 1R introduction to R program.pptx
Abapprogrammingoverview 090715081305-phpapp02
Chapter 1abapprogrammingoverview-091205081953-phpapp01
ABAP Programming Overview
chapter-1abapprogrammingoverview-091205081953-phpapp01
Chapter 1 Abap Programming Overview
Abapprogrammingoverview 090715081305-phpapp02
Lab 3 Set Working Directory, Scatterplots and Introduction to.docx
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
Raspberry Pi - Lecture 5 Python for Raspberry Pi
List Processing in ABAP
Python Variable Types, List, Tuple, Dictionary
Ad

More from Rudy Martinez (13)

PPTX
CS 151Exploration of python
PPTX
CS 151 Graphing lecture
PPTX
CS 151 Classes lecture 2
PPTX
CS 151 Classes lecture
PPTX
CS 151 Standard deviation lecture
PPTX
CS 151 Midterm review
PPTX
CS 151 dictionary objects
PPTX
CS151 Functions lecture
PPTX
Lecture4
PPTX
Lecture01
PPTX
Lecture02
PPTX
Lecture03
PPTX
Lecture01
CS 151Exploration of python
CS 151 Graphing lecture
CS 151 Classes lecture 2
CS 151 Classes lecture
CS 151 Standard deviation lecture
CS 151 Midterm review
CS 151 dictionary objects
CS151 Functions lecture
Lecture4
Lecture01
Lecture02
Lecture03
Lecture01

Recently uploaded (20)

PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Cell Types and Its function , kingdom of life
PPTX
Institutional Correction lecture only . . .
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Classroom Observation Tools for Teachers
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
GDM (1) (1).pptx small presentation for students
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
2.FourierTransform-ShortQuestionswithAnswers.pdf
Cell Types and Its function , kingdom of life
Institutional Correction lecture only . . .
A systematic review of self-coping strategies used by university students to ...
STATICS OF THE RIGID BODIES Hibbelers.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
Final Presentation General Medicine 03-08-2024.pptx
Classroom Observation Tools for Teachers
Pharmacology of Heart Failure /Pharmacotherapy of CHF

CS 151 CSV output

  • 1. Computer Science 151 An introduction to the art of computing CSV writing Rudy Martinez
  • 2. CS151 Spring 2019 Notes on Homework 2a 1. Open file and pass to file object (myfile, open(file,r)) 2. Call csv reader on file object and pass to variable (myfile) 3. Create global dictionary to hold values (DATA = {}) a. Key = date, b. Value = [tmax, tmin] 4. Create counter for the number of records. 5. For every line in myfile variable a. If counter == 0 then eat header i. Increment counter b. Else i. If tmax is not empty AND tmin is not empty 1. Then write row to global dictionary (DATA) 2. Increment counter ii. Else: 1. Increment counter (drop row from final list) 6. Open file and pass to file object (myNewFile, open(newfile, w)) 7. For every row in dictionary {DATA) (for loop) a. Write row to myNewFile object (csv.writerow)
  • 3. CS151 Spring 2019 Writing Dictionary or List to CSV This is just like writing a normal file. #Create file object! myNewFile = open(‘test1.csv’, ‘w’) # This will overwrite test1 each time it runs! #Create variable to write to writer = csv.writer(myNewFile) #write each row in Data List/Dictionary to file for row in DATA: writer.writerow(row) # write a single row (as retrieved by for loop) Output: ['1994-04-01', '74', '35'] ['1994-04-02', '68', '38'] ['1994-04-04', '70', '']
  • 4. CS151 Spring 2019 Writing Dictionary or List to CSV This is an alternate way of writing to a csv file. #Create file object! myNewFile = open(‘test2.csv’, ‘w’) # This will overwrite test1 each time it runs! #Create variable to write to writer = csv.writer(myNewFile) #write each row in Data List/Dictionary to file writer.writerows(DATA) # write all rows at once! Output: ['1994-04-01', '74', '35'] ['1994-04-02', '68', '38'] ['1994-04-04', '70', '']
  • 5. CS151 Spring 2019 Paths on Linux and Windows ● Paths are basically the same for Linux and Mac! ● Linux =(‘/home/[username]/Documents/myfile.txt’) ● Windows =(r ‘C:Users[username]Documentsmyfile.txt’) ○ Must add ‘r’ to the command for it to read the backslash ● Linux doesn’t need to be told what drive (C: on windows) ● Windows uses a backslash (‘’) and Linux/Mac use a forward slash (‘/’) Notes for Linux/Mac: if you see a tilde (‘~’) that usually means home folder: ‘~/Documents’ == ‘/home/bob/Documents’
  • 6. CS151 Spring 2019 Summation Exercise DATA = [‘1’,’1’,’1’,’1’] summation = 0 for row in DATA: summation += int(row[0]) print(str(sumation)) Output: 4 * A note your CSV files are all strings!
  • 7. CS151 Spring 2019 Summation Example 2 # New list with 5 elements of type int DATA2 = [1,1,1,1,1] # Initialize sum variable to 0 summation1 = 0 # can use sum function from python! summation1 = sum(DATA2) # Print result print(summation1) Output: 5
  • 8. CS151 Spring 2019 There is a difference! DATA = [‘1’,’1’,’1’,’1’] DATA2 = [1,1,1,1,1] These are two completely different lists DATA == strings DATA2 == ints !Sum only works on list of ints, or floats!
  • 9. CS151 Spring 2019 Conversions ● Convert from string to int ○ int(‘1’) -> 1 ● Convert from int to string ○ str(1) -> ‘1’ ● Convert from string to datetime object! from datetime import datetime from datetime import date myString = ‘1994-04-01’ myDateVar2 = datetime.strptime(myString, '%Y-%m-%d').date() myString myDateVar2.year myDateVar2.month myDateVar2.day ‘1994-04-01’ 1994 04 01
  • 10. CS151 Spring 2019 Lets convert some lists DATA3 = ['1','2','34','56'] # Now lets convert in place! for counter in range(0, len(DATA3), 1): # Grab string and convert to integer and store in variable myInt = int(DATA3[counter]) # Copy back to list (remember it's mutable so we can do this) DATA3[counter] = myInt # Now I can just call sum on DATA3 since it's all int print('Summation of whole list = ', str(sum(DATA3))) print('Average of list items is = ', str(sum(DATA3)/len(DATA3))) Output: Summation of whole list = 93 Average of list items is = 23.25
  • 11. CS151 Spring 2019 Let’s Review ● Write out what you need to do for the homework using the algorithm given. ○ Think about how to eat the elephant.