如何根据输入的单词显示某些文件中的数据?

时间:2019-01-15 11:48:40

标签: python file text-files

我有一个程序,可以让您输入数据并将其保存到文本文件中。我想做的是让用户在开头输入他们的名字,然后将他们输入的任何数据保存到该名字,因此当他们再次输入相同的名字时,它将显示数据。但是当输入新名称时,将没有数据。

名称输入提示

name=input("Enter name:")

以下允许用户在调用此函数时输入数据并将其保存到文本文件中

def enterproduct():
    number=input("enter food: ")

    price=input("enter calories in food consumed: ")

    # should remove any leading or trailing spaces
    number = number.strip()
    price = price.strip()

    # write data to the file as one line (comma delimited)
    line =number+","+price+"\n" #put all the data together
    with open("inventory.txt","a") as file:
        file.write(line) #write product data
    file.close()

enterproduct()

在下面,您可以查看在调用时输入到文本文件中的数据

def seeproducts():
    print("ENTERED DATA")
    print("....................")
    products=[] 
    file = open("inventory.txt", "r")
    for line in file:
        products.append(line)
    file.close()

    for item in products: 
        print(item)
        currentline = item.split(",") #split data where there is a comma
        prodnumber = currentline[0]
        price = currentline[1]

seeproducts()

上面只是我的代码的一个小示例,在程序的其他部分创建了多个文本文件,您可以在此处看到整个内容:https://pastebin.com/KsdqfBA9

我希望输出为:

*Enter name: matt<br>
enter food: apple<br>
enter calories: 50*

*ENTERED DATA<br>
.............<br>
apple,50*

然后,当我重新启动程序并再次输入matt时:

*Enter name: matt<br>
enter food: orange<br>
enter calories: 30*

*apple,50<br>
orange,30*

如上所示,该程序已将“ apple,50”保存为无光。但是,如果我输入一个新名称,它不应显示“ apple,50”

使用此处显示的代码,我得到的输出是不保存名称属性的数据,而是保存所有内容,而与输入的名称无关。

1 个答案:

答案 0 :(得分:0)

名称未与产品或卡路里保存在同一行。

您可以通过将名称添加到文件名来保存产品来更改此名称。 或通过将名称添加到保存的行中。