简体   繁体   English

在 csv 文件的行中添加一个字符

[英]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.我想设计一个 function 来查找我输入的卡号,如果那里没有 x,则在数字之前的 have 列中插入一个 x。 I've added the csv example and relevant code below我在下面添加了 csv 示例和相关代码

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.最好将整个数据结构读入原生 Python 数据结构(例如列表列表),修改内存中的数据,然后重写整个文件。

This will be even easier if you use a library specialized for this like Pandas .如果您使用专门用于此的库,例如Pandas ,这将更加容易。 For example, first instead of including the card number directly in the Card column, make a separate column for it like this:例如,首先不要将卡号直接包含在 Card 列中,而是为它创建一个单独的列,如下所示:

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.如果您的集合变得更大或将经常修改,您可能需要考虑使用SQLite 数据库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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