所以这是代码,它在循环中但仅存储最后一条记录:
try:
with open('records.csv', 'a') as csv_file:
for url in urls:
if url.strip() != '':
print('Processing URL:- '+url)
data = fetch_data(url)
csv_file.write(data)
status = 'OK'
csv_file.close()
except Exception,e:
status = 'FAIL'
print str(e)
finally:
with open('process.log', 'a') as the_file:
ts = time.strftime("%H:%M")
the_file.write(ts+'\t'+url+'\t'+status+'\n')
if driver is not None:
driver.quit()
records.csv
仅保存最后一条记录
答案 0 :(得分:1)
file.write
不会在文件中添加换行符,因此它可能会处理所有内容,但只会向文件中添加一行。
一些挑剔:
csvfile.close()
阻止,因此无需执行with
。status="OK"
,只需在循环上方设置一次。
datalines = []
for url in urls:
if url.strip():
datalines.append(fetch_data(url))
csvfile.write("\n".join(datalines))