SlideShare a Scribd company logo
1 of 11
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

What's hot

16858 memory management2
16858 memory management216858 memory management2
16858 memory management2
Aanand Singh
 
Date & time functions in VB.NET
Date & time functions in VB.NETDate & time functions in VB.NET
Date & time functions in VB.NET
A R
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory Mapping
Qundeel
 

What's hot (20)

Joc live session
Joc live sessionJoc live session
Joc live session
 
Algorithms: II
Algorithms: IIAlgorithms: II
Algorithms: II
 
Pa1 session 5
Pa1 session 5Pa1 session 5
Pa1 session 5
 
hash
 hash hash
hash
 
Radix sort
Radix sortRadix sort
Radix sort
 
16858 memory management2
16858 memory management216858 memory management2
16858 memory management2
 
CBSE Python List Assignment
CBSE Python List AssignmentCBSE Python List Assignment
CBSE Python List Assignment
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sort
 
Implementation of queue using singly and doubly linked list.
Implementation of queue using singly and doubly linked list.Implementation of queue using singly and doubly linked list.
Implementation of queue using singly and doubly linked list.
 
Python List Comprehensions
Python List ComprehensionsPython List Comprehensions
Python List Comprehensions
 
Lab 1
Lab 1Lab 1
Lab 1
 
Date & time functions in VB.NET
Date & time functions in VB.NETDate & time functions in VB.NET
Date & time functions in VB.NET
 
Radix and shell sort
Radix and shell sortRadix and shell sort
Radix and shell sort
 
Algorithms: I
Algorithms: IAlgorithms: I
Algorithms: I
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory Mapping
 
Chunked, dplyr for large text files
Chunked, dplyr for large text filesChunked, dplyr for large text files
Chunked, dplyr for large text files
 
Getting started - Warewolf Syntax
Getting started - Warewolf Syntax  Getting started - Warewolf Syntax
Getting started - Warewolf Syntax
 
CS151 FIle Input and Output
CS151 FIle Input and OutputCS151 FIle Input and Output
CS151 FIle Input and Output
 
Work flow
Work flowWork flow
Work flow
 
Stack & Queue
Stack & QueueStack & Queue
Stack & Queue
 

Similar to CS 151 CSV output

Abapprogrammingoverview 090715081305-phpapp02
Abapprogrammingoverview 090715081305-phpapp02Abapprogrammingoverview 090715081305-phpapp02
Abapprogrammingoverview 090715081305-phpapp02
wingsrai
 
Chapter 1abapprogrammingoverview-091205081953-phpapp01
Chapter 1abapprogrammingoverview-091205081953-phpapp01Chapter 1abapprogrammingoverview-091205081953-phpapp01
Chapter 1abapprogrammingoverview-091205081953-phpapp01
tabish
 
chapter-1abapprogrammingoverview-091205081953-phpapp01
chapter-1abapprogrammingoverview-091205081953-phpapp01chapter-1abapprogrammingoverview-091205081953-phpapp01
chapter-1abapprogrammingoverview-091205081953-phpapp01
tabish
 
Abapprogrammingoverview 090715081305-phpapp02
Abapprogrammingoverview 090715081305-phpapp02Abapprogrammingoverview 090715081305-phpapp02
Abapprogrammingoverview 090715081305-phpapp02
tabish
 
Lab 3 Set Working Directory, Scatterplots and Introduction to.docx
Lab 3 Set Working Directory, Scatterplots and Introduction to.docxLab 3 Set Working Directory, Scatterplots and Introduction to.docx
Lab 3 Set Working Directory, Scatterplots and Introduction to.docx
DIPESH30
 

Similar to CS 151 CSV output (20)

Cs 151 dictionary writer
Cs 151 dictionary writerCs 151 dictionary writer
Cs 151 dictionary writer
 
CS 151 homework2a
CS 151 homework2aCS 151 homework2a
CS 151 homework2a
 
CS151 Deep copy
CS151 Deep copyCS151 Deep copy
CS151 Deep copy
 
CS 151 Date time lecture
CS 151 Date time lectureCS 151 Date time lecture
CS 151 Date time lecture
 
Lec04-CS110 Computational Engineering
Lec04-CS110 Computational EngineeringLec04-CS110 Computational Engineering
Lec04-CS110 Computational Engineering
 
Data import-cheatsheet
Data import-cheatsheetData import-cheatsheet
Data import-cheatsheet
 
R_CheatSheet.pdf
R_CheatSheet.pdfR_CheatSheet.pdf
R_CheatSheet.pdf
 
Unit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxUnit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptx
 
ABAP Programming Overview
ABAP Programming OverviewABAP Programming Overview
ABAP Programming Overview
 
Abapprogrammingoverview 090715081305-phpapp02
Abapprogrammingoverview 090715081305-phpapp02Abapprogrammingoverview 090715081305-phpapp02
Abapprogrammingoverview 090715081305-phpapp02
 
Chapter 1abapprogrammingoverview-091205081953-phpapp01
Chapter 1abapprogrammingoverview-091205081953-phpapp01Chapter 1abapprogrammingoverview-091205081953-phpapp01
Chapter 1abapprogrammingoverview-091205081953-phpapp01
 
chapter-1abapprogrammingoverview-091205081953-phpapp01
chapter-1abapprogrammingoverview-091205081953-phpapp01chapter-1abapprogrammingoverview-091205081953-phpapp01
chapter-1abapprogrammingoverview-091205081953-phpapp01
 
Chapter 1 Abap Programming Overview
Chapter 1 Abap Programming OverviewChapter 1 Abap Programming Overview
Chapter 1 Abap Programming Overview
 
Abapprogrammingoverview 090715081305-phpapp02
Abapprogrammingoverview 090715081305-phpapp02Abapprogrammingoverview 090715081305-phpapp02
Abapprogrammingoverview 090715081305-phpapp02
 
Lab 3 Set Working Directory, Scatterplots and Introduction to.docx
Lab 3 Set Working Directory, Scatterplots and Introduction to.docxLab 3 Set Working Directory, Scatterplots and Introduction to.docx
Lab 3 Set Working Directory, Scatterplots and Introduction to.docx
 
C++
C++C++
C++
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiRaspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry Pi
 
List Processing in ABAP
List Processing in ABAPList Processing in ABAP
List Processing in ABAP
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Cheat Sheet for Stata v15.00 PDF Complete
Cheat Sheet for Stata v15.00 PDF CompleteCheat Sheet for Stata v15.00 PDF Complete
Cheat Sheet for Stata v15.00 PDF Complete
 

More from Rudy Martinez (13)

CS 151Exploration of python
CS 151Exploration of pythonCS 151Exploration of python
CS 151Exploration of python
 
CS 151 Graphing lecture
CS 151 Graphing lectureCS 151 Graphing lecture
CS 151 Graphing lecture
 
CS 151 Classes lecture 2
CS 151 Classes lecture 2CS 151 Classes lecture 2
CS 151 Classes lecture 2
 
CS 151 Classes lecture
CS 151 Classes lectureCS 151 Classes lecture
CS 151 Classes lecture
 
CS 151 Standard deviation lecture
CS 151 Standard deviation lectureCS 151 Standard deviation lecture
CS 151 Standard deviation lecture
 
CS 151 Midterm review
CS 151 Midterm reviewCS 151 Midterm review
CS 151 Midterm review
 
CS 151 dictionary objects
CS 151 dictionary objectsCS 151 dictionary objects
CS 151 dictionary objects
 
CS151 Functions lecture
CS151 Functions lectureCS151 Functions lecture
CS151 Functions lecture
 
Lecture4
Lecture4Lecture4
Lecture4
 
Lecture01
Lecture01Lecture01
Lecture01
 
Lecture02
Lecture02Lecture02
Lecture02
 
Lecture03
Lecture03Lecture03
Lecture03
 
Lecture01
Lecture01Lecture01
Lecture01
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 

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.