这是我的数据库,名为myDB.txt
:
28273139
iPhone
5.50
30
5
35
81413852
Book
1.50
43
10
55
文本文件数据库遵循以下格式
Product Code
Product Name
Price
Current Stock
Reorder Stock (the lowest the stock can go)
Target Stock
现在,我要更新iPhone数据。这是iPhone数据。
28273139
iPhone
5.50
30
5
35
它使用8位产品代码来标识产品。
我写了下面的代码。
userCode = "28273139"
newstock = "29"
database = open('myDB.txt','r+')
while(str(userCode) not in next(database)):
pass
else:
for i in range(3):
line = next(database)
replace = line.replace(line,newstock)
database.write(replace)
我想将列表的第4个值从30更改为29,我将其声明为变量newstock。该程序向下移动3行,因为数据库中每个产品的格式都相同,并用此新值替换该行。
我需要更新iPhone数据的结果-
28273139
iPhone
5.50
29
5
35
但是,此方法不起作用。
我每次都会收到一个错误。
AttributeError: 'str' object has no attribute 'readlines'
有人可以帮助解决我的问题吗?我编写的代码是否正确才能产生所需的结果?
当您将文本文件配置为key:value对时(例如dict
python中的构造,或另一个DB中的值,例如SQL),这要容易得多。然后,您可以在满足该值时简单地设置一个哨兵值,然后在替换正确的行时将其取消设置。
因此,如果将文本格式更改为:
ProductCode <value>
ProductName <value>
Price <value>
CurrentStock <value>
ReorderStock <value>
Targetstock <value>
然后,您可以执行以下操作:
ProductCode = "28273139"
NewStock = "29"
SentinelValue = 0
with open('myDB.txt', 'r+') as database:
for line in database:
(key, val) = line.split()
if key == "ProductCode":
if val == ProductCode:
SentinelValue = 1
if key != "ProductCode":
if key == "CurrentStock":
if SentinelValue == 1:
line = line.replace(val, NewStock)
print line
它有点脏,可以肯定会被清理,但是更加冗长。另外,请注意,空格很重要,因为它在分割行时用作定界符。
您可能还会注意到我没有写文件:至少对于python 2.7来说,似乎存在一个问题,我不能替换一行文本,只能用追加f.write()
。这段代码可以正常工作并将其替换为stdout,写文件的解决方法是将所有行简单地写到新文件中:
ProductCode = "28273139"
NewStock = "29"
SentinelValue = 0
fout = open('newDB.txt', 'w')
with open('myDB.txt', 'r+') as database:
for line in database:
(key, val) = line.split()
if key == "ProductCode":
if val == ProductCode:
SentinelValue = 1
if key != "ProductCode":
if key == "CurrentStock":
if SentinelValue == 1:
line = line.replace(val, NewStock)
fout.write(line)
print line
然后,您可以编写逻辑以根据需要替换文件。但是,我非常建议您看一下如何在实际的SQL数据库中进行读写。我希望这有帮助!^^
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句