SlideShare ist ein Scribd-Unternehmen logo
1 von 11
Downloaden Sie, um offline zu lesen
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.

Weitere ähnliche Inhalte

Was ist angesagt?

Joc live session
Joc live sessionJoc live session
Joc live sessionSIT Tumkur
 
16858 memory management2
16858 memory management216858 memory management2
16858 memory management2Aanand Singh
 
CBSE Python List Assignment
CBSE Python List AssignmentCBSE Python List Assignment
CBSE Python List AssignmentAmit Sethi
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sortVasim Pathan
 
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.central university of bihar
 
Python List Comprehensions
Python List ComprehensionsPython List Comprehensions
Python List ComprehensionsYos Riady
 
Date & time functions in VB.NET
Date & time functions in VB.NETDate & time functions in VB.NET
Date & time functions in VB.NETA R
 
Radix and shell sort
Radix and shell sortRadix and shell sort
Radix and shell sortAaron Joaquin
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory MappingQundeel
 
Chunked, dplyr for large text files
Chunked, dplyr for large text filesChunked, dplyr for large text files
Chunked, dplyr for large text filesEdwin de Jonge
 
Getting started - Warewolf Syntax
Getting started - Warewolf Syntax  Getting started - Warewolf Syntax
Getting started - Warewolf Syntax Carol Vanden Bussche
 
CS151 FIle Input and Output
CS151 FIle Input and OutputCS151 FIle Input and Output
CS151 FIle Input and OutputRudy Martinez
 

Was ist angesagt? (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
 

Ähnlich wie CS 151 CSV output

Cs 151 dictionary writer
Cs 151 dictionary writerCs 151 dictionary writer
Cs 151 dictionary writerRudy Martinez
 
CS 151 Date time lecture
CS 151 Date time lectureCS 151 Date time lecture
CS 151 Date time lectureRudy Martinez
 
Lec04-CS110 Computational Engineering
Lec04-CS110 Computational EngineeringLec04-CS110 Computational Engineering
Lec04-CS110 Computational EngineeringSri Harsha Pamu
 
R_CheatSheet.pdf
R_CheatSheet.pdfR_CheatSheet.pdf
R_CheatSheet.pdfMariappanR3
 
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.pptxSreeLaya9
 
ABAP Programming Overview
ABAP Programming OverviewABAP Programming Overview
ABAP Programming Overviewsapdocs. info
 
Abapprogrammingoverview 090715081305-phpapp02
Abapprogrammingoverview 090715081305-phpapp02Abapprogrammingoverview 090715081305-phpapp02
Abapprogrammingoverview 090715081305-phpapp02tabish
 
Abapprogrammingoverview 090715081305-phpapp02
Abapprogrammingoverview 090715081305-phpapp02Abapprogrammingoverview 090715081305-phpapp02
Abapprogrammingoverview 090715081305-phpapp02wingsrai
 
Chapter 1abapprogrammingoverview-091205081953-phpapp01
Chapter 1abapprogrammingoverview-091205081953-phpapp01Chapter 1abapprogrammingoverview-091205081953-phpapp01
Chapter 1abapprogrammingoverview-091205081953-phpapp01tabish
 
chapter-1abapprogrammingoverview-091205081953-phpapp01
chapter-1abapprogrammingoverview-091205081953-phpapp01chapter-1abapprogrammingoverview-091205081953-phpapp01
chapter-1abapprogrammingoverview-091205081953-phpapp01tabish
 
Chapter 1 Abap Programming Overview
Chapter 1 Abap Programming OverviewChapter 1 Abap Programming Overview
Chapter 1 Abap Programming OverviewAshish Kumar
 
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.docxDIPESH30
 
def ddg(poultry) # Write your code here and edit the return .docx
def ddg(poultry)    # Write your code here and edit the return .docxdef ddg(poultry)    # Write your code here and edit the return .docx
def ddg(poultry) # Write your code here and edit the return .docxsimonithomas47935
 
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 PiMohamed Abdallah
 
List Processing in ABAP
List Processing in ABAPList Processing in ABAP
List Processing in ABAPsapdocs. info
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionarySoba Arjun
 

Ähnlich wie 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
 
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
 
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++
 
def ddg(poultry) # Write your code here and edit the return .docx
def ddg(poultry)    # Write your code here and edit the return .docxdef ddg(poultry)    # Write your code here and edit the return .docx
def ddg(poultry) # Write your code here and edit the return .docx
 
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
 

Mehr von Rudy Martinez

Mehr von 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
 

Kürzlich hochgeladen

The Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsThe Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsEugene Lysak
 
In - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxIn - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxAditiChauhan701637
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...raviapr7
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxraviapr7
 
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRADUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRATanmoy Mishra
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesCeline George
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxMYDA ANGELICA SUAN
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxSaurabhParmar42
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxKatherine Villaluna
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxDr. Asif Anas
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxiammrhaywood
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationMJDuyan
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...Nguyen Thanh Tu Collection
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxDr. Santhosh Kumar. N
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE
 
How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17Celine George
 
Philosophy of Education and Educational Philosophy
Philosophy of Education  and Educational PhilosophyPhilosophy of Education  and Educational Philosophy
Philosophy of Education and Educational PhilosophyShuvankar Madhu
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxKatherine Villaluna
 

Kürzlich hochgeladen (20)

Personal Resilience in Project Management 2 - TV Edit 1a.pdf
Personal Resilience in Project Management 2 - TV Edit 1a.pdfPersonal Resilience in Project Management 2 - TV Edit 1a.pdf
Personal Resilience in Project Management 2 - TV Edit 1a.pdf
 
The Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsThe Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George Wells
 
In - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxIn - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptx
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptx
 
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRADUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 Sales
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptx
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptx
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptx
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptx
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
 
Prelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quizPrelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quiz
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive Education
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptx
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024
 
How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17
 
Philosophy of Education and Educational Philosophy
Philosophy of Education  and Educational PhilosophyPhilosophy of Education  and Educational Philosophy
Philosophy of Education and Educational Philosophy
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
 

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.