我有一个股票系统。 数据写入文件,如下所示:(产品代码,名称,成本价格,价格,数量)
1004, table, 10, 20, 45
1005, chair, 6, 13, 30
1006, lamp, 2, 5, 10
以下代码用于更新股票数量:
def test():
items = []
itemname = input("Enter itemname: ")
with open('Stockinventory.txt') as inputfile:
for line in inputfile:
items.append(line.strip().split(','))
with open('Stockinventory.txt') as inputfile:
for num, line in enumerate(inputfile, 0):
if itemname in line:
newline = (items[num])
newline = line.split(", ")
print ("SIN: %s" % newline[0])
print ("Itemname: %s" % newline[1])
print ("Retail price: %s" % newline[2])
print ("Costprice: %s" % newline[3])
print ("Quantity Available: %s" % newline[4])
choice = input("Would you like to update quantity? y/n")
if choice == 'y':
newquantity = input("Enter new quantity: ")
newline[4] = newquantity
print(newline)
items[num] = newline
print(items)
writetrue = '1'
else:
startup()
if writetrue == '1':
f = open('Stockinventory.txt', 'w')
f.write(str(items))
f.close()
else:
print("No change")
startup()
代码正确地更改了数量但是当我将数组重写到文件时,它看起来像这样:
[['1004', 'table', '10', '20', '30'], ['1005', ' chair', ' 6', ' 13', ' 30'], ['1006', ' lamp', ' 2', ' 5', ' 10']]
在这种情况下,表的数量更改为30。 如何将数据写回原来的文件?
答案 0 :(得分:4)
您正在编写整个列表的str()
输出,而不是将这些行重新格式化为原始格式。
使用逗号重新加入行,在每行后添加换行符:
with open('Stockinventory.txt', 'w') as f:
for row in items:
f.write(', '.join(row) + '\n')
如果您对逗号后面的空格不太感兴趣,您还可以使用csv
module一次编写列表:
import csv
with open('Stockinventory.txt', 'w', newline='') as f:
csv.writer(f).writerows(items)
我当然会使用csv
模块读取您的文件:
import csv
with open('Stockinventory.txt', 'r', newline='') as f:
items = list(csv.reader(f, skipinitialspace=True))
一次性将整个文件读入列表列表。
你读了两次文件;没有必要,不是当你已经在列表中有所有行时:
for row in enumerate(items):
if row[1] == itemname:
print("SIN: %s" % row[0])
print("Itemname: %s" % row[1])
print("Retail price: %s" % row[2])
print("Costprice: %s" % row[3])
print("Quantity Available: %s" % row[4])
choice = input("Would you like to update quantity? y/n")
if choice == 'y':
newquantity = input("Enter new quantity: ")
row[4] = newquantity
print(', '.join(row))
writetrue = '1'
else:
startup()
我们直接改变row
;将items
再次写入csv
文件将包含更改的数量。
答案 1 :(得分:0)
在这种情况下,不需要多次打开同一个文件。你可以一气呵成地做到这一切。如果您不想要任何标准库导入,并且可读性很重要,那么您可以稍微重构一下:
itemname = raw_input("Enter item name\n>>>")
with open("Stockinventory.txt", "r+") as file:
# Search for item (per line)
while True:
position = file.tell()
thisline = file.readline()
if itemname in thisline:
break
# Print result
for tag, val in zip(["SIN", "Itemname",
"RetailPrice", "Costprice",
"Quantity Available"],
thisline.split(", ")):
print tag, ":", val
# Query update
choice = raw_input("Would you like to update "
"quantity?\n>>>")
if choice in ("y", "Y"):
newquan = raw_input("Enter new quantity\n>>>")
newline = "".join([thisline.rsplit(",",1)[0],
", ", newquan, "\n"])
remline = file.read()
file.seek(position)
file.write(newline + remline)