【发布时间】:2018-01-10 17:36:20
【问题描述】:
我有一个大小合适的网页抓取脚本,其中包含 25K+ url 的输入到一个单独的页面抓取函数中,该函数在所有 url 中运行一个 for 循环。在 for 循环结束时,它将结果写入 csv。 目前,我有这个代码:
if link == url[0]:
# Creating the file and writing headers with the first entry and closing after
# the first entry to go from write mode to append mode
with open(file_Name, 'w') as f:
stats_df.to_csv(f)
record_Counter = record_Counter + 1
print ('Two entries for one game recorded. Counter = ' + str(record_Counter))
elif link == url[1]:
# Opening the file in append mode and keeping it open for the majority of the loop
# and writing with no headers
f = open(file_Name, mode = 'a')
stats_df.to_csv(f, header=False)
record_Counter = record_Counter + 1
print ('Two entries for one game recorded. Counter = ' + str(record_Counter))
elif link == url[-1]:
# Writing the final entry of this page and closing the file
stats_df.to_csv(f, header=False)
record_Counter = record_Counter + 1
print ('Two entries for one game recorded. Counter = ' + str(record_Counter))
f.close()
else:
# Writing all entries in between
stats_df.to_csv(f, header=False)
record_Counter = record_Counter + 1
print ('Two entries for one game recorded. Counter = ' + str(record_Counter))
以前,我有这个:
if link == url[0]:
with open(file_Name, 'w') as f:
stats_df.to_csv(f)
record_Counter = record_Counter + 1
print ('Two entries for one game recorded. Counter = ' + str(record_Counter))
else:
with open(file_Name, 'a') as f:
stats_df.to_csv(f)
record_Counter = record_Counter + 1
print ('Two entries for one game recorded. Counter = ' + str(record_Counter))
我对更简单的代码的担忧是我打开和关闭 csv 文件 25K 次,这会减慢我的运行时间。我目前担心的是在打开 f 的异常情况下内存损坏的问题。
我是否有理由担心我的任何一个问题?感谢您的宝贵时间。
【问题讨论】:
-
代码已损坏(标识) - 您的来源中就是这种情况?
-
我会选择第二种方法,获得部分结果似乎比获得第一种方法更好。重新开始抓取也更容易 - 只需使用 25k 网址中的第 n 个条目重新开始。
-
纯粹出于兴趣-。我每天都会看到几个网络抓取 python 线程,我总是问自己:“为什么”?
-
Patrick:不,代码在我的实际代码中工作并且当前正在运行。在将其放入代码块的 SO 格式中时,我可能犯了一些格式错误。
-
“打开和关闭 csv 文件 25K 次”似乎很简单……您是否真的对此进行了基准测试以查看它是否存在某种瓶颈?我会选择第二种形式,如果您的代码运行速度太慢,那么 profile 它会确定上述是否真的是一个问题。这有点过早的优化。
标签: python csv for-loop file-io