我正在尝试编写一个程序,该程序使用函数打开文件,然后使用文件中的行来玩纸牌游戏,但我不断收到此错误。
Traceback(最近一次调用最后一次):文件 “/ home / ecunning / Documents / Treasure Hunt Game Lab”,第115行,in drawCard()文件“/ home / ecunning / Documents / Treasure Hunt Game Lab”,第102行,在drawCard中 deck = readDeck(file)文件“/ home / ecunning / Documents / Treasure Hunt Game Lab”,第26行,在readDeck中 infile = open(fileName,'r')TypeError:强制转换为Unicode:需要字符串或缓冲区,找到类型
这是我的代码:
def getfileName():
fileName = raw_input("What is the name of the file?: ")
return fileName
while (fileName != fileDescription):
print("Invalid file name. Select an appropriate file: ")
fileName = raw_input("What is the name of the file?: ")
return fileName
def readDeck(fileName):
infile = open(fileName , 'r')
deck = []
for card in infile:
print card
return deck
def getCardType(deck):
cardType = input("What is the location of the card would you like to extract from the deck: ")
card = deck[cardType]
return card
print card
while (cardType > len(deck)):
print "This location is not in the deck. Re-enter a location that is within the list"
cardType = input("What is the location of the card would you like to extract from the deck: ")
card = deck[cardType]
return card
print card
newDeck = deck.remove(str(card))
cardGroup = card[:1]
return cardGroup
print cardGroup
if str(cardGroup) == ruby:
print "This card is a ruby"
elif str(cardGroup) == emerald:
print "This card is an emerald"
elif str(cardGroup) == coal:
print "This card is coal"
else:
print "This card is a diamond"
def getCardValue(card):
cardValue = card[2:]
cardAmount = int(cardValue)
return cardAmount
def displayList(card):
drawnCards = []
drawnCards.append(card)
drawnCards.sort()
print ("List of drawn cards: ") ,drawnCards.sort()
def getPosition():
cardType = input("What is the location of the card would you like to extract from the deck: ")
card = newDeck[cardType]
return card
print card
while (cardType > len(deck)):
print "This location is not in the deck. Re-enter a location that is within the list"
cardType = input("What is the location of the card would you like to extract from the deck: ")
card = deck[cardType]
return card
print card
def drawCard():
cardtotal = 0
while (cardtotal < winValue):
getfileName()
deck = readDeck(file)
cardType = getCardType(deck)
if (str(cardGroup) != coal):
cardtotal = cardtotal + cardAmount
print cardtotal
getCardValue(card)
displayList(card)
cardType = getPosition()
else:
print "You drew a coal card. The game is over"
print "You have drawn 21 points! You win!"
drawCard()
任何帮助都会很棒!!谢谢。
答案 0 :(得分:1)
您收到此错误是因为您在该行上传入function
对象而不是string
对象。我想象你要做的就是这样称呼这个方法:
deck = readDeck(getfileName())
您的程序中似乎还有很多关于变量范围和控制流的问题,因此我建议您read up on your problems然后查看您的程序并解决您看到的所有问题