如何在文本文件中声明一行作为变量?

时间:2016-10-18 10:58:00

标签: python file lines readlines

例如,我打开了一个文本文件,找到了一个用户想要“购买”的产品。产品列在记事本文本文件中,产品名称则为新行,然后是产品成本,例如

radiators
0.50
fridge
0.50

这是我到目前为止所做的:

product = input("What product would you like?")
userfile = open ("products.txt","r")
    lines = userfile.readlines()
    for i in range(0, len(lines)):
        line = lines[i]
        if product in (line):
            found = True
            print("Found " + line)
            print("This product is " + lines[i+1])
            print("This product costs " +lines[i+2])

我需要将lines[i+2]声明为变量,因此我可以将它乘以整数。有没有办法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

试试这个:

产品=输入("您想要什么产品?")

userfile = open ("products.txt","r")
lines = userfile.readlines()

for line in lines:
   line = line.rstrip('\n')
   if product in line:
        found = True
        print("Found " + line)
        print("This product is " + lines[i+1])
        print("This product costs " + int(lines[i+2]))