我有一个html scraper,可以从网站上获取商品和价格的标题。 有一段时间我想运行这个刮刀来更新我的价格,这样做我也希望保留旧的。
我的csv第一次保存标题和价格是这样的:
Title1, price1, 'END'
Title2, price2, 'END'
Title3, price3, 'END'
我使用以下方法将新价格与旧价格进行比较:
ind = row.index('END')
lastprijs = row[ind-1]
print lastprijs
if lastprijs != prijstitel:
row.pop(ind)
row.append(prijstitel)
row.append("END")
如果找到(并设置)了一个值,我用
更新csvwith open('out.csv', 'a') as out:
tester = csv.writer(out)
tester.writerow(row)
如果没有找到值,我用相同的行更新csv:
else:
with open('out.csv', 'a') as out:
tester = csv.writer(out)
row.append("addedddd") #add a new line.
tester.writerow(row)
然而,运行后我的csv的输出如下:
Item1, price1, 'END'
Item2, price2, 'END'
Item3, price3, 'END'
Item1, price1, 'END'
item1, price1, 'END'
Item2, price2, 'END'
Item3, price3, 'END'
Item1, price1, 'END'
item1, price1, 'END'
Item2, price2, 'END'
Item2, price2, 'END'
Item3, price3, 'END'
Item1, price1, 'END'
依旧...... 我该如何解决这个问题?
**完整的代码**
def updateprices(prijstitel, titelprijs):
with open('pricewatch.csv', 'r') as csvfileadjust:
filereader = csv.reader(csvfileadjust)
print titelprijs
if titelprijs == "Gembird externe Hardeschijf behuizing met USB 2.0 aansluiting":
prijstitel = 'EDITED PRIJS!'
for row in filereader:
header = row
print header
print " ---- "
if titelprijs in row:
ind = row.index('END')
lastprijs = row[ind-1]
print lastprijs
if lastprijs != prijstitel:
row.pop(ind)
row.append(prijstitel)
row.append("END")
with open('out.csv', 'a') as out:
tester = csv.writer(out)
tester.writerow(row)
else:
with open('out.csv', 'a') as out:
tester = csv.writer(out)
row.append("addedddd") #add a new line.
tester.writerow(row)
答案 0 :(得分:1)
你的问题是正确的,
这可以解决您的问题
x=0
while x < 20: Or length of csv file.
updateprices("10,00","TITELS", x)
x+=1
def updateprices(prijstitel, titelprijs, var):
with open(csvfile, 'r') as csvfileadjust: #open the file
filereader = csv.reader(csvfileadjust)
row = list(islice(filereader,var+1))[-1] #get all lines till var+1
if titelprijs in row: #if the title is in the row
ind = row.index('END') #search for END in that List
lastprijs = row[ind-1]
print lastprijs
if lastprijs != prijstitel: #if lastprijs is not equal to prijstitel ( 9,99 != 10,00)
row.pop(ind) #drop the last item in list ("END")
row.append(prijstitel) #add the new prijstitel (10,00)
row.append("END")
with open('out.csv', 'a') as out:
tester = csv.writer(out)
tester.writerow(row) #Write to csv file
else: #if the title is not in the row
with open('out.csv', 'a') as out:
tester = csv.writer(out)
tester.writerow(row) #write (or copy) the line