我有两个定义的函数,其中都需要使用找到的文本文件中的一行。然而,因为它们是两种不同的功能,我不能在不搜索该行的文本文件的那一行中使用“行”。所以我想要找到找到的“行”的值,并将其分配给一个变量,以便在后面的函数中使用,但是我得到“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