Basically want to extract values from a csv file, and create a global dictionary that I can go ahead and use for my other functions.
I don't know if I used the right approach in creating a class so bear with me.
def spread_parse extracts the values I want from the csv file however, when run the function. My dictionary "pick" returns blank. I know this approach works because if I just combine function "def spread_parse" and function "def write" into a single function , it'll create a separate file with the values I want. The issue is that I would like to create other functions with the newly added values that is contained in my "pick" dictionary and with a single function, those values will just be restricted to that function. Please correct me if I am incorrect.
import csv
class Parse:
def __init__(self, filename):
self.filename = filename
self.picks = {}
def spread_parse(self):
"""Parses csv file"""
f = open(self.filename)
csv_f = csv.reader(f)
a = []
b = []
# Add players names to players
for row in csv_f:
a.append(row[2])
# Have to repull csv file to add prices
f = open(self.filename)
csv_f = csv.reader(f)
# Add prices of each player
for row in csv_f:
b.append(row[5])
# Copy a & b lists into players and prices to remove Players,
# Names columns
players = a[1:]
prices = b[1:]
self.picks = dict(zip(players, prices))
def write(self):
# create a file name based on week
file = 'PGA_Picks23.txt'
with open(file, 'w') as f:
for key, value in self.picks.items():
picky = (key, value)
f.writelines("\n" + str(picky))
Then I go ahead and run the class in a separate file.
import Eh as e
e.Parse('DKSal.csv').spread_parse()
e.Parse('DKSal.csv').write()
It just returns a blank file when I run both of those functions.
You're creating two separate objects. You need to create a single Parse object and call both of the methods from it:
import Eh as e
parse = e.Parse('DKSal.csv')
parse.spread_parse()
parse.write()
Unless there is a specific reason why you don't want to use pandas , I suggest that you do. Pandas have a wide range of input and output tools. Normally, one reads the data into a DataFrame which is like a spreadsheet with rows and columns. Any row or any column by itself is called a Series . You can create dictionaries from dataframes using the to_dict
method. The code could look similar to this:
import pandas as pd
df = pd.read_csv(your_csv)
# Do your data cleaning here.
# To create a dictionary
as_dict = df.to_dict(orient='list')
# To write back to a csv after some manipulations
df.to_csv(filename)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.