CSV文件无法从my cs打印特定值/实体

2024-06-16 14:39:42 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我正在计划的一个游戏,我想创建一段代码,将我游戏中所有物品的列表中的一个特定值写入玩家的库存(例如:玩家获得物品“potion”,这需要在CSV中搜索物品中的potion,然后将相关信息放入CSV)。但是,每当我运行代码时,就会出现错误“TypeError:'\u io.TextIOWrapper'object is not subscriptable”

我试着研究和询问同行,但我得到的最接近于一个明确的解决方案是有人提到写从CSV列表,但他们没有解释更多。希望有人能为我详细说明这一点或提供一个更简单的解决办法

import csv

allitems = open("ALLITEMS.csv")
checkallitems = csv.reader(allitems)

playerinv = open("INVENTORY.csv")
checkinv = csv.reader(playerinv)

item = input("")

for x in checkallitems:
    print(allitems[x][0])
    if item == allitems[x][0]:
        playerinv.write(allitems[x][0]+"\n")
allitems.close()
playerinv.close()

Tags: csv代码游戏列表close玩家openitem
1条回答
网友
1楼 · 发布于 2024-06-16 14:39:42

问题是allitems是由open返回的file object,语句for x in checkallitems在此类文件的行上迭代,因此,您尝试在该文件中使用list作为索引。此外,您必须在写入模式下打开INVENTORY.csv(使用“w”或“a”)才能对其进行写入

x代替allitems[x]。下面的代码片段应该可以完成这项工作:

for x in checkallitems:
    if item == x[0]:
        playerinv.write(x[0]+"\n")

所以,完整的代码可以是:

代码

import csv

allitems = open("ALLITEMS.csv")
checkallitems = csv.reader(allitems)

playerinv = open("INVENTORY.csv", 'a')
checkinv = csv.reader(playerinv)

item = input("")

for x in checkallitems:
    if item == x[0]: # Check if the item is equal to the first item on the list
        playerinv.write(x[0]+"\n")

allitems.close()
playerinv.close()

我不知道你想完成什么,所以我尽量坚持你的代码

如果只希望在当前项目列表中找到用户提供的项目时才写入该项目,则可以执行以下操作:

代码

import csv

allitems = open("ALLITEMS.csv")
checkallitems = csv.reader(allitems)

playerinv = open("INVENTORY.csv", 'a')
checkinv = csv.reader(playerinv)

item = input("")

for x in checkallitems:
    if item in x: # Check if the item is in the current list
        playerinv.write(item +"\n")

allitems.close()
playerinv.close()

我希望这能帮助你。告诉我这些对你是否有用,否则,告诉我哪里出了问题

相关问题 更多 >