[英]Assign line from .txt file to a variable python for later use
我有2个定义的函数,其中两个都需要使用找到的文本文件中的一行。 但是,因为它们是两种不同的功能,所以我不能在不搜索文本文件的那一行中使用“ line”。 因此,我想使用找到的“线”的值并将其分配给变量以在以后的函数中使用,但是我得到的错误是未定义“ variable_Line”。
第一个功能部分:
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_cart
接受一个参数:
def add_cart(variable_Line):
然后可以这样称呼它:
add_cart(variable_Line) #second function defined below
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.