【问题标题】:How do I declare a line in a text file as a variable?如何将文本文件中的一行声明为变量?
【发布时间】:2016-10-18 10:58:00
【问题描述】:

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

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] 声明为一个变量,这样我就可以像整数一样将它相乘。有没有办法可以做到这一点?

【问题讨论】:

  • 你不需要将它声明为变量(这甚至意味着什么?),你只需要将字符串转换为数字。
  • 好的,谢谢,但是我该怎么做呢??
  • 我不使用 Python,但你的代码看起来还是错误的:如果 product"radiators",它将输出 Found radiators This product is 0.50 This product costs fridge
  • 哦。在我把它放在这里之前,我稍微改变了一下程序——真正的程序不是这样工作的????我用了一个例子

标签: python file lines readlines


【解决方案1】:

试试这个:

product = input("你想要什么产品?")

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]))

【讨论】:

  • 感谢您的回复,我已尝试按照您的建议在代码中使用“int”几次,但总是出现此错误
  • ValueError: int() 以 10 为底的无效文字:'0.50\n'
  • @mollyclare 那是因为0.5 不是整数。
  • 啊,好吧,也许我可以改一下数字.. 非常抱歉,非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 2019-12-02
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 2021-09-04
  • 2017-07-12
相关资源
最近更新 更多