尝试从一个字典列表创建一个 Stock 实例列表,然后计算总成本: >>> import fileparse >>> with open('Data/portfolio.csv') as lines: ... portdicts = fileparse.parse_csv(lines, select= ['name','shares','price'], types=[str,int,float]) ... >>> portfolio = [ stock.Stock(d['name'], d['shares'], d['price']) for d in portdicts] >>> portfolio [<stock.Stock object at 0x10c9e2128>, <stock.Stock object at 0x10c9e2048>, <stock.Stock object at 0x10c9e2080>, <stock.Stock object at 0x10c9e25f8>, <stock.Stock object at 0x10c9e2630>, <stock.Stock object at 0x10ca6f748>, <stock.Stock object at 0x10ca6f7b8>] >>> sum([s.cost() for s in portfolio]) 44671.15。写fileparse.py
时间: 2024-02-28 16:52:28 浏览: 64
好的,以下是一个简单的fileparse模块的示例代码,用于解析CSV格式的文件:
```python
import csv
import os
def parse_csv(lines, select=None, types=None, has_headers=True, delimiter=',', silence_errors=False):
rows = csv.reader(lines, delimiter=delimiter)
# 读取列头
headers = []
if has_headers:
try:
headers = next(rows)
except csv.Error as e:
if not silence_errors:
print(f"Error reading headers: {e}")
# 如果有指定列,则仅保留指定的列
if select and headers:
indices = [headers.index(colname) for colname in select]
headers = select
else:
indices = []
# 如果指定了类型,则将指定列转换为指定类型
if types:
types = [str] * len(headers) if not types else types
try:
rows = [[func(val) for func, val in zip(types, row)] for row in rows]
except ValueError as e:
if not silence_errors:
print(f"Error parsing row: {e}")
return None
# 组合每一行的数据
records = []
for row in rows:
if not row:
continue
if indices:
row = [row[index] for index in indices]
if has_headers:
record = dict(zip(headers, row))
else:
record = tuple(row)
records.append(record)
return records
```
这个模块可以解析CSV格式的文件,并将每一行的数据组合成一个字典或者元组。接下来可以用这个模块来解析投资组合的CSV文件,然后创建Stock实例列表,并计算总成本。
阅读全文