0
\$\begingroup\$

I am trying to import a .csv file and save data in objects for later manipulation in Python. I am very new to coding so please do let me know my fundamental errors.

import csv
import os
import time
import numpy
import itertools

def __init__(p):        
    p.playerFile = csv.reader(open("dk.csv", "rb"))
    p.playerList = []
    p.playerName = ''
    p.playerPosition = ''
    p.PlayerGameInfo = ''
    p.playerPrice = 0

def loadCSV(p):
    for row in p.playerFile:
        playerObject = Player()
        playerObject.setPlayerName(row[1])     # Store player name
        playerObject.setPlayerPosition(row[0]) # Store player position
        playerObject.setPlayerGameInfo(row[3]) # Store player team
        playerObject.setPlayerPrice(row[2])    # Store player price

def getPlayerName(p):
    return p.PlayerName

def getPosition(p):
    return p.playerPosition

def getGameInfo(p):
    return p.PlayerGameInfo

def getPrice(p):
    return p.PlayerPrice

def setPlayerName(p, player):
    p.playerName = name

def setPlayerPosition(p, playerPosition):
    p.playerPosition = position

def setPlayerGameInfo(p, PlayerGameInfo):
    p.PlayerGameInfo = team

def setPlayerPrice(p, playerPrice):
    p.playerPrice = price

with open('~/dk.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        print (row)
\$\endgroup\$

closed as off-topic by IEatBagels, Stephen Rauch, Toby Speight, Graipher, Dannnno Oct 3 '18 at 20:59

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – IEatBagels, Toby Speight, Graipher, Dannnno
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    \$\begingroup\$ Could you provide an example of how you use this code elsewhere in your program? \$\endgroup\$ – 200_success Nov 10 '14 at 2:25
4
\$\begingroup\$

Style

Use snake_case instead of mixedCase when in Python. In general, follow PEP 8.

Implementation

It seems you have a Player class defined somewhere. Then, you use global functions as getters and setters. This has two problems:

  1. In OOP, getters and setters should be instance methods, e.g. of the Player class.
  2. Python is not Java. Pythonic code wouldn't normally use getters and setters.

Design

Judging by loadCSV, each row of a CSV file will become a Player object. However, all Players do is store attributes for getting and setting. Save the hassle by using a dictionary for a player. Then just store all your dictionaries in a list.

To understand this code, you will need to understand comprehensions.

import csv

# Map row to dictionary (dictionary comprehension)
def player(column_names, row):
    return {column_names[column]: data for column, data in enumerate(row) if column < len(column_names)}

# Map CSV file to list of dictionaries (list comprehension)
players = [player(['name', 'position', 'game_info', 'price'], row) for row in csv.reader(open('dk.csv', 'r'))]

Running this code on the following CSV file

Louis Fernando,Batter,Washington,400
Hose Ricardo,Pitcher,San Fernando,900

sets players to a list of dictionaries as below.

[{'game_info': 'Washington',
  'name': 'Louis Fernando',
  'position': 'Batter',
  'price': '400'},
 {'game_info': 'San Fernando',
  'name': 'Hose Ricardo',
  'position': 'Pitcher',
  'price': '900'}]

Then player objects can be accessed like so

print(players[0]['game_info']) # prints Washington
players[1]['name'] = "James Jones"

Notes

Types

This doesn't take care of types, e.g. the price field maps to a string, not a number. I'm not exactly sure what you're doing overall, so I'll leave that to you.

CSV Format

Columns in your CSV file beyond those named in column_names will be ignored.

e.g. passing four names (['name', 'position', 'game_info', 'price']) to player when a row in the CSV file contains five columns.

Louis Fernando,Batter,Washington,400,lol
Hose Ricardo,Pitcher,San Fernando,900

will produce the same result as the first example.

\$\endgroup\$
  • \$\begingroup\$ Lambda expressions allow creation of anonymous functions. When you assign a name (player), a def statement is appropriate. \$\endgroup\$ – Janne Karila Nov 10 '14 at 13:50
  • \$\begingroup\$ Luke, when I run the codeit returns an error: Traceback (most recent call last): File "/home/kenny/v3.py", line 8, in <module> players = [player(['name', 'position', 'game_info', 'price'], row) for row in csv.reader(open('/home/kenny/dk.csv', 'r'))] File "/home/kenny/v3.py", line 5, in player return {column_names[column]: row[column] for column in range(len(row))} File "/home/kenny/v3.py", line 5, in <dictcomp> return {column_names[column]: row[column] for column in range(len(row))} IndexError: list index out of range \$\endgroup\$ – Kenny G Nov 10 '14 at 20:22
  • \$\begingroup\$ @KennyG Note I'm using Python 3. I have edited player to handle this by adding if index < len(column_names) to the comprehension. The result of this change is explained in Notes. \$\endgroup\$ – user27318 Nov 10 '14 at 21:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.