-1

I'm trying to create a checklist program for my sports cards. I would like to design a function that looks up the cardnumber I entered and inserts an x into the have column before the number if there already isn't an x there. I've added the csv example and relevant code below

Have,Card
,1 Will Harridge
,2 Warren Giles
,3 Elmer Valo - Kansas City Athletics
,4 Carlos Paula - Washington Senators
,5 Ted Williams - Boston Red Sox
,6 Ray Boone - Detroit Tigers
import csv


def addcard(card):
    for i in CardData:



Cardlist = open('1956topps.csv')
CardListReader = csv.reader(Cardlist)
CardData = csv.writer(CardListReader)


while True:
    Option = int(input(" Choose your option: '\n' 1. Add a card to the collection '\n' "
                       "2. Delete a card form the collection '\n' 3. Print a list of cards you need '\n' "
          "4. Print a list of cards you have '\n' 5. Look up individual card info '\n' 6. Quit'\n'"))
    if Option == 1:
        card = input('Enter the card number you want to add \n')
        addcard(card)
CostaK
  • 23
  • 4
  • are you trying to replace the comma with an X? – Evorage Jul 16 '20 at 17:50
  • No I'm trying to place an x before the comma – CostaK Jul 16 '20 at 17:52
  • you probably want to use [multiline strings](https://stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-string) for those prompts, manual `\n` in the middle of the line is kind of gross. Also you creating a `csv.writer` from the csv reader, which doesn't really make sense, what you would want to do is open the file again (after closing it after reading it) for writing and write all the data back with a newly added X in the right spot. – Tadhg McDonald-Jensen Jul 16 '20 at 17:54
  • 1
    @CostaK yourstring = "X" + yourstring – Evorage Jul 16 '20 at 17:54

1 Answers1

0

You will find this fairly difficult to do by directly manipulating text files; it's better to just read in the entire data structure into a native Python data structure (e.g. list of lists), modify the data in-memory, then rewrite the entire file.

This will be even easier if you use a library specialized for this like Pandas. For example, first instead of including the card number directly in the Card column, make a separate column for it like this:

Number,Card,Have
1,Will Harridge,0
2,Warren Giles,0
3,Elmer Valo - Kansas City Athletics,0
4,Carlos Paula - Washington Senators,0
5,Ted Williams - Boston Red Sox,0
6,Ray Boone - Detroit Tigers,0

then:

import pandas as pd

filename = '1956topps.csv'
cards = pd.read_csv(filename, dtype={'Number': int, 'Have': bool}, index_col='Number')

# E.g. mark card 5 as owned:
cards.loc[5]['Have'] = True

# Write back out to the same file
cards.to_csv(filename)

If your collection grows larger or will be modified frequently you might want to consider a SQLite database instead.

Iguananaut
  • 21,810
  • 5
  • 50
  • 63