我有兩個定義的函數,其中都需要使用找到的文本文件中的一行。然而,因爲它們是兩種不同的功能,我不能在不搜索該行的文本文件的那一行中使用「行」。所以我想要找到找到的「行」的值,並將其分配給一個變量,以便在後面的函數中使用,但是我得到「variable_Line」未定義的錯誤。將.txt文件中的行分配給一個變量python供以後使用
科第一功能:
while (len(code) == 8):
with open('GTIN Products.txt', 'r') as search:
for line in search:
line = line.rstrip('\n')
if code in line:
variable_Line = line #This is where i try to assign contents to a variable
print("Your search found this result: "+line) #this prints the content of line
add_cart() #second function defined below
二級功能
def add_cart():
add_cart = ""
while add_cart not in ("y", "n"):
add_cart = input("Would you like to add this item to your cart? ")
if add_cart == "y":
receipt_list.append(variable_Line) #try to use the variable here but get an error
if add_cart == "n":
break
爲了便於閱讀,我強烈建議您不要在名爲'add_card'的函數內創建一個名爲'add_card'的局部變量。 – Jeff
我看到你從哪裏來,謝謝你的提示! :) – AntsOfTheSky