Python 3.x 如何根据两个不同文本文件中的相同行打印值

Python 3.x 如何根据两个不同文本文件中的相同行打印值,python-3.x,Python 3.x,我希望用户输入保存在文件中的特定产品名称,因此我希望打印出保存在不同文件中的产品价格,但无法这样做 我刚开始编程,所以对我来说是新的 def find_in_file(f) : myfile = open("file1.txt") products = myfile.read() products = products.splitlines() if f in products: return "Product is in list" e

我希望用户输入保存在文件中的特定产品名称,因此我希望打印出保存在不同文件中的产品价格,但无法这样做

我刚开始编程,所以对我来说是新的

def find_in_file(f) :
    myfile = open("file1.txt")
    products =  myfile.read()
    products = products.splitlines()
    if f in products:
        return "Product is in list"
    else:
        return "Product is not in list"

def printing_in_file(p) : 
    myprice = open("file2.txt")
    price =  myprice.read()
    price = price.splitlines()
        return price

if code in sec_code.values():
    product = input("Enter product name:   ")
    print(printing_in_file(p))
我希望价格是输出,但我得到的名称“p”没有定义。

下面的答案可行,但不完整,因为您没有提供输入文件的示例

您提供的代码没有“p”变量,因此我将其替换为变量product。我在函数find_product中为返回创建了bool值,该函数名为find_in_file。如果输入的产品名称完全匹配,则会产生问题,然后返回布尔值True。接下来,代码将调用函数find_product_price,该函数在产品名称的_文件中被命名为printing_。我必须创建包含产品名称和价格的文件,因为您没有提供示例文件作为问题的一部分

这段代码可以工作,但有局限性,因为我不知道输入文件或sec_代码值的确切格式。有了额外的信息,这段代码可以得到改进,或者一些新的东西可以用更好的东西来代替它

祝你在这个编码问题上好运

def find_product(product_name) :
  inventory_file = open('tmpFile.txt', 'r', encoding='utf-8')
  products =  inventory_file.read()
  products = products.splitlines()
  if product_name in products:
     return True
  else:
     return False

def find_product_price(product_name) :
  product_prices =  open('tmpFile01.txt', 'r', encoding='utf-8')
  prices =  product_prices.read()
  price = prices.splitlines()
  if product_name in price:
     return price

product = input("Enter product name: ")
product_search = find_product(product)
if product_search == True:
  print ('The product is available.')
  print(find_product_price(product))
  # outputs 
  ['cisco router $350']

elif product_search == False:
  print (f'{product} are not available for purchase.')

你注意到你的两个函数有相同的名字吗?什么是sec_代码?sec_代码是安全代码。那部分很好用。也许你是说在文件产品中打印?但是在函数中根本没有使用p…我猜测当前显示的代码会在引发NameError之前引发SyntaxError/IndentationError。请发表一篇文章,重复你的问题。这通常更有利,有助于调试。