简体   繁体   English

如何替换 Python 中的一行

[英]How do I replace a line in Python

I am trying to write a program in Python for an assessment where I have to update a stock file for a shop.我正在尝试用 Python 编写一个程序进行评估,我必须在其中更新商店的库存文件。

My instructions我的指示

My code so far:到目前为止我的代码:

#open a file in read mode
file = open("data.txt","r")
#read each line of data to a vairble
FileData = file.readlines()
#close the file
file.close()

total = 0 #create the vairble total
AnotherItem = "y" # create
while AnotherItem == "y" or AnotherItem  == "Y" or  AnotherItem ==  "yes" or  AnotherItem ==  "Yes" or  AnotherItem ==  "YES":
        print("please enter the barcode")
        UsersItem=input()
        for line in  FileData:
                #split the line in to first and second section
                barcode = line.split(":")[0]
                item = line.split(":")[1]
                price = line.split(":")[2]
                stock = line.split(":")[3]

                if barcode==UsersItem:
                    file = open("data.txt","r")
                    #read each line of data to a vairble
                    FileData = file.readlines()
                    #close the file
                    file.close()
                    print(item +"       £" + str(float(price)/100) + "      Stock: " + str(stock))
                    print("how many do you want to buy")
                    HowMany= input()
                    total+=float(price) * float( HowMany)
                    file = open("data.txt","a")
                    StockLevel=float(stock)
                    file.write(item + ":" + price + ":" +str(float((StockLevel-float(HowMany)))))
                    file.close()
                    print("Do you want to buy another item? [Yes/No]")
                    AnotherItem = input()
        if AnotherItem == "n" or "N" or "no" or "No" or "NO":
                print("total price: £"+ str(total/100))

When I try to update my stock file it writes to end of the data file, instead of over the line I want it to.当我尝试更新我的股票文件时,它会写入数据文件的末尾,而不是超出我想要的行。

file = open("data.txt", "a")

Opens the file in append mode, means writing to the end of the file without overwriting data (adding to it, not changing).以追加模式打开文件,意味着在不覆盖数据的情况下写入文件末尾(添加数据,而不是更改数据)。

Use

file = open("data.txt", "w")

Instead, to flush the file contents and overwrite them.相反,刷新文件内容并覆盖它们。


If you have some lines, and you only want to change the last do as follows:如果您有一些行,并且只想更改最后一行,请执行以下操作:

data = open("data.txt").read().split("\n")

get an array of the file lines.获取文件行的​​数组。

data[-1] = new_line_contents

change the last line to the new content.将最后一行更改为新内容。

open("data.txt", "w").write("\n".join(data))

write back with flushing the new data (join the elements in data with newline between them)通过刷新新数据回写(将数据中的元素与它们之间的换行符连接起来)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM