Visitar URL original
report.py update · dabeaz-course/practical-python@955c0d8 · GitHub
Skip to content

Commit 955c0d8

Browse files
committed
report.py update
1 parent 7b1fd14 commit 955c0d8

6 files changed

Lines changed: 60 additions & 21 deletions

File tree

‎Work/.DS_Store‎

2 KB
Binary file not shown.

‎Work/Data/.DS_Store‎

6 KB
Binary file not shown.

‎Work/Data/portfolio.csv‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1-
name,shares,price
2-
"AA",100,32.20
3-
"IBM",50,91.10
4-
"CAT",150,83.44
5-
"MSFT",200,51.23
6-
"GE",95,40.37
7-
"MSFT",50,65.10
8-
"IBM",100,70.44
1+
name,shares,price
2+
AA,100,32.2
3+
IBM,50,91.1
4+
CAT,150,83.44
5+
MSFT,200,51.23
6+
GE,95,40.37
7+
MSFT,50,65.1
8+
IBM,100,70.44
9+
ROKU,50,134.56
10+
JPM,50,93.45
11+
BAC,206,23.54
12+
DFKG,182,37.45

‎Work/pcost.py‎

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,5 @@
1-
# pcost.py
2-
# Exercise 1.27: Reading a data file
3-
#
4-
# Now that you know how to read a file, let’s write a program to perform a simple calculation.
5-
#
6-
# The columns in portfolio.csv correspond to the stock name, number of shares, and purchase price of a single stock
7-
# holding. Write a program called pcost.py that opens this file, reads all lines, and calculates how much it cost to
8-
# purchase all of the shares in the portfolio.
9-
#
10-
# Hint: to convert a string to an integer, use int(s). To convert a string to a floating point, use float(s).
11-
#
12-
# Your program should print output such as the following:
13-
# Exercise 1.27
1+
2+
import csv
143

154

165
def portfolio_cost(filename):

‎Work/portfolio.csv.numbers‎

122 KB
Binary file not shown.

‎Work/report.py‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,49 @@
11
# report.py
22
#
33
# Exercise 2.4
4+
import csv
5+
6+
portfolio = []
7+
8+
9+
# def read_portfolio(filename):
10+
#
11+
# """ Computes the total cost (shares*price) of a portfolio file """
12+
#
13+
# with open(filename, 'rt') as rows:
14+
# header = next(rows)
15+
# print(header)
16+
# for row in rows:
17+
# line = row.split(',')
18+
# holding = (line[0], int(line[1]), float(line[2]))
19+
# portfolio.append(holding)
20+
# return portfolio
21+
#
22+
#
23+
# cost = read_portfolio('Data/portfolio.csv')
24+
# print(cost)
25+
26+
# Now as a dictionary:
27+
def read_portfolio(filename):
28+
29+
""" Computes the total cost (shares*price) of a portfolio file """
30+
31+
with open(filename, 'rt') as file:
32+
header = next(file)
33+
total = 0
34+
for line in file:
35+
line2 = line.split(',')
36+
total += (int(line2[1])) * (float(line2[2]))
37+
return total
38+
39+
40+
cost = read_portfolio('Data/portfolio.csv')
41+
print(cost)
42+
43+
44+
45+
46+
47+
48+
49+

0 commit comments

Comments
 (0)