我正在尝试用Python编写程序进行评估,我必须更新商店的库存文件。
到目前为止我的代码:
#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))
当我尝试更新我的库存文件时,它会写入数据文件的末尾,而不是我想要的那一行。
答案 0 :(得分:0)
file = open("data.txt", "a")
以附加模式打开文件,意味着写入文件末尾而不覆盖数据(添加数据,不更改)。
使用
file = open("data.txt", "w")
相反,要刷新文件内容并覆盖它们。
如果您有一些行,并且您只想按如下方式更改最后一行:
data = open("data.txt").read().split("\n")
获取文件行数组。
data[-1] = new_line_contents
将最后一行更改为新内容。
open("data.txt", "w").write("\n".join(data))
回写并刷新新数据(将数据中的元素与新行相连接)