我正在嘗試編寫一個程序,它使用函數來打開文件,然後使用文件中的行來玩一個紙牌遊戲,但我一直在這個錯誤。TypeError:強制轉換爲Unicode:需要字符串或緩衝區,找到類型,函數
Traceback (most recent call last): File "/home/ecunning/Documents/Treasure Hunt Game Lab", line 115, in drawCard() File "/home/ecunning/Documents/Treasure Hunt Game Lab", line 102, in drawCard deck = readDeck(file) File "/home/ecunning/Documents/Treasure Hunt Game Lab", line 26, in readDeck infile = open(fileName , 'r') TypeError: coercing to Unicode: need string or buffer, type found
這裏是我的代碼:
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()
任何幫助將是巨大的!謝謝。
你有多個問題,當前是'deck = readDeck(file)'你正在傳遞'file'這是一個python類/類型,它應該是我想象的' readDeck(getfileName())'。 'return fileName'之後的while循環無法訪問,您似乎正在訪問多個未定義的變量 –