[英]Assign line from .txt file to a variable python for later use
I have 2 defined functions in which both need to use a line from a text file that is found. 我有2个定义的函数,其中两个都需要使用找到的文本文件中的一行。 However because they are two different functions i can't use "line" in the one which doesn't search the text file for that line.
但是,因为它们是两种不同的功能,所以我不能在不搜索文本文件的那一行中使用“ line”。 So i want to take the value of "line" which was found and assign it to a variable to use in the later functions but i get the error that "variable_Line" is not defined.
因此,我想使用找到的“线”的值并将其分配给变量以在以后的函数中使用,但是我得到的错误是未定义“ variable_Line”。
Section of first function: 第一个功能部分:
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
Second function 第二功能
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
Make add_cart
accept an argument: 使
add_cart
接受一个参数:
def add_cart(variable_Line):
You can then call it like this: 然后可以这样称呼它:
add_cart(variable_Line) #second function defined below
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.