有人知道如何替换文本文件中的单词吗?你知道吗
我的股票档案里有一行:
bread 0.99 12135479 300 200 400
当我打印“productline”时,我希望能够将我的第4个单词(在本例中为“300”)替换为由以下代码的nstock部分创建的新数字:
for line in details: #for every line in the file:
if digits in line: #if the barcode is in the line
productline=line #it stores the line as 'productline'
itemsplit=productline.split(' ') #seperates into different words
price=float(itemsplit[1]) #the price is the second part of the line
current=int(itemsplit[3]) #the current stock level is the third part of the line
quantity=int(input("How much of the product do you wish to purchase?\n"))
if quantity<current:
total=(price)*(quantity) #this works out the price
print("Your total spent on this product is:\n" + "£" +str(total)+"\n") #this tells the user, in total how much they have spent
with open("updatedstock.txt","w") as f:
f.writelines(productline) #writes the line with the product in
nstock=int(current-quantity) #the new stock level is the current level minus the quantity
我的代码不会将第4个字(即当前库存水平)替换为新库存水平(nstock)
实际上,你可以使用正则表达式来达到这个目的。你知道吗
输出波形如下: '面包0.99 12135479优优200 400'
希望这就是你要找的;)
相关问题 更多 >
编程相关推荐