简体   繁体   中英

Adding a character to a row in a csv file

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)

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 (eg 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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM