如何将两个文件中的数据添加在一起?

时间:2019-01-13 16:21:20

标签: python file text-files

我正在用python创建一个卡路里计数程序,该程序创建两个文本文件,一个用于消耗的食物卡路里,另一个用于燃烧的卡路里运动,我需要从食物卡路里中减去燃烧的卡路里,但是两者的信息都是在单独的文本文件中,如何创建另一个文本文件并将这两个文件中的数据添加到其中?

我尝试过将文件包含在返回其数据的函数中,然后添加添加函数,以便可以从消耗的卡路里中减去消耗的卡路里,但是似乎无法添加或连接函数。

Excercise.txt是在上面的其他代码块中创建的,还输入了锻炼时间,此处为保持简单起见,此处省略了锻炼时间。该块读取,添​​加并在外壳中显示代码以供练习。

def liftnumber():
    total=0
    products=[]
    file = open("excercises.txt", "r")
    for line in file: #put data from file int6o propdytc list
        products.append(line)
    file.close()


    for item in products: # show products
        currentline = item.split(",") #split data where tyhe is a comma
        total=total+int(currentline[0])
    print("Total calories expended:",total*100)

此代码块将所有食物的卡路里加到inventory.txt中,并且此代码块也沿最后一个代码行进行操作,在该代码行中其他地方创建了stock.txt和输入的食物。唯一的不同是,该数据库有2个数据段,以逗号分隔;卡路里和食物名称,而最后一个有一个摘要:运动时间

def finishday():
    total=0
    print("HERE'S HOW YOU DID TODAY")
    print("-----------------")
    products=[] ##create a list that holds all foods from inventory.txt
    file = open("inventory.txt", "r")
    for line in file: #put data from file int6o propdytc list
        products.append(line)
    file.close()

    for item in products: # show products
        currentline = item.split(",") #split data where tyhe is a comma
        total=total+int(currentline[1])

    print("Total calories consumed:",total)

    liftnumber()

如果您无法使用上面的代码复制问题,请尝试以下整个程序:

允许用户在主循环之外进行选择的功能:

def mainmenu():
    print("------------------------")
    print("ETCHAPP")
    print("------------------------")
    print("1> enter a new food")
    print("2> see foods")
    print("3> delete something")
    print("4> enter excercises")
    print("5> finish day")
    print("6> see excercises")

    print("x> exit program")
    choice = input("Enter your choice: ")
    choice=choice.strip()
    return(choice)

def enterproduct():
    print("ENTER A NEW FOOD")
    print("------------------------")
    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()


def seeproducts():
    print("REPORT OF PRODUCTS")
    print("-----------------")
    products=[] #create a list that holds all foods from inventory.txt
    file = open("inventory.txt", "r")
    for line in file: #put data from file into propdytc list
        products.append(line)
    file.close()

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

# This one allows user to enter excercise times
def enterlift():
    print("ENTER A NEW EXCERCISE")
    print("------------------------")
    print("(must be 30 bpm over normal heart rate)")
    num=input("enter number of hours excercised: ")

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

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

# This one adds all the excercise times together
def liftnumber():
    total=0
    products=[] #create a list that holds all foods from inventory.txt
    file = open("excercises.txt", "r")
    for line in file: #put data from file int6o propdytc list
        products.append(line)
    file.close()


    for item in products: # show products
        currentline = item.split(",") #split data where tyhe is a comma
        total=total+int(currentline[0])
    print("Total calories expended:",total*100)



# This one allows user to see excercise times entered
def seelift():
    print("HERE'S HOW YOU'RE DOING")
    print("-----------------")

    total=0
    products=[] #create a list that holds all foods from inventory.txt
    file = open("excercises.txt", "r")
    for line in file: #put data from file int6o propdytc list
        products.append(line)
    file.close()

    for item in products: # show products
        currentline = item.split(",") #split data where tyhe is a comma
        total=total+int(currentline[0])
    print("Total hours excercised:",total)
    print("Total calories expended:",total*100)

# This finishes a day and begins the next one
def finishday():
    total=0
    print("HERE'S HOW YOU DID TODAY")
    print("-----------------")
    products=[] #create a list of which weill hold all products from the 
file inventory.txt
    file = open("inventory.txt", "r")
    for line in file: #put data from file int6o propdytc list
        products.append(line)
    file.close()

    for item in products: # show products
        currentline = item.split(",") #split data where tyhe is a comma
        total=total+int(currentline[1])

    print("Total calories consumed:",total)

    liftnumber()

#This deletes things
def deleteproduct():
    products=[] #create a list whcih will hold all products from file 
inventory.txt
    currentindex=0 #this will be use4d to get an index
    #position od utem to delete in list
    file = open("inventory.txt","r")
    for line in file: #put data frpom file into product
        products.append(line)
    file.close()
    seeproducts() #show all the products
    #enter product number to delete
    deletethis=input("Enter name of the food to delete: ")

    #loop through produces find matching number
    #delete product from list
    for item in products: #show products
        currentline = item.split(",") #split data where comma
        prodnumber = currentline[0] #get the item's product number
        if prodnumber==deletethis:
            break #found product to delete
        currentindex=currentindex+1 #increment index for next product
    del products[currentindex] #delete product at this index

    #erase provios file
    file = open('inventory.txt','r+')
    file.truncate(0)

    #write new file from list
    for item in products:
        with open("inventory.txt","a") as file:
            file.write(item) #write product data
    file.close()


#main program starts here
choice=""
while choice!="x": #loop to allows user to choice
    #exit when the user chooses 'x'

    choice=mainmenu()
    if choice=="1":
        enterproduct()
    if choice=="2":
        seeproducts()
    if choice=="3":
        deleteproduct()
    if choice=="5":
        finishday()
    if choice=="4":
        enterlift()
    if choice=="6":
        seelift()

预期:

我希望创建一个新文件“ totalcal.txt”,并将“ inventory.txt”(仅食品卡路里数,而不是食品名称)和“ excercises.txt”的内容加在一起(如果这似乎令人困惑,但是通过“加在一起”,我的意思是我希望将运动卡路里消耗的卡路里从所消耗的食物卡路里中减去(减去),并通过打印“总计消耗的卡路里”,并且该数字可以是负数(如果消耗的卡路里大于消耗的卡路里)或正数(如果消耗的卡路里大于消耗的卡路里)

我会在liftnumber()调用下方的结尾附近的finishday()内部调用此函数

以上是我认为可以完成的方式,但是如果您可以通过其他方式获得下面的结果,我也将不胜感激。

因此确切的预期输出是:

您今天的情况如何
.............................
消耗的总热量:number1
消耗的总热量:number2
燃烧或消耗的总卡路里:1-2
..........................

现实:

我忘记了确切的错误,但是这给了我一个错误的信息,那就是根据我试图解决问题的方式,无法将功能添加在一起。

谢谢

1 个答案:

答案 0 :(得分:0)

我对Google进行了快速搜索,发现您可以通过执行以下操作添加两个(或更多)文本文件:

filenames = ['file1.txt', 'file2.txt']
with open('result.txt', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read())

所以我弄清楚了,我还设法通过创建一个新函数并返回数据来减去总卡路里,这使我可以将函数本身用作单个数据,但是我喜欢,这让我解决了这个问题。

对不起,我的问题很困惑,但现在我已经知道了。

谢谢