简体   繁体   中英

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. 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. 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.

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:

def add_cart(variable_Line):

You can then call it like this:

add_cart(variable_Line) #second function defined below

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM