如何在Python脚本中添加循环功能和1分钟的延迟?

时间:2019-07-04 00:36:11

标签: python sleep

我有一个Python脚本,该脚本从数据文件中读取各个股票ID名称,然后为每个唯一ID调用URL,并写入输出文件。我想将此代码更改为仅执行5个ID,然后等待60秒,再执行5个,再等待60秒,依此类推,直到列表完成。我当时在考虑使用Sleep(60)函数并创建某种类型的Loop,但不确定在Python中执行此操作的最佳方法。任何人都可以帮忙修改下面的代码来完成此操作吗?谢谢。

# Import the library
import urllib.request

url_base = "https://www.website.com/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={}&outputsize=full&apikey=123&datatype=csv"

dest_path = "C:/Users/ScriptTest/Date/{}.csv"

symbols = open("symbols.txt").read().strip().split("\n")

for symbol in symbols:
  url = url_base.format(symbol) # Add the curret symbol to base URL
  dest = dest_path.format(symbol) # Add the curret symbol as the file name
  urllib.request.urlretrieve(url, dest) # Save the current file 

**想要执行高于5倍的最后3行,然后暂停60秒,然后执行接下来的5个符号,依此类推,直到列表用尽。

2 个答案:

答案 0 :(得分:0)

我想以上方法都可以,

from time import sleep

n = 1
for symbol in symbols:
  url = url_base.format(symbol) # Add the curret symbol to base URL
  dest = dest_path.format(symbol) # Add the curret symbol as the file name
  urllib.request.urlretrieve(url, dest) # Save the current file
  if n % 5 == 0:
    sleep(60)
  n += 1

答案 1 :(得分:0)

#add import time
c=0
for symbol in symbols:

  if c==5:
     time.sleep(60)
     c=0
  url = url_base.format(symbol) # Add the curret symbol to base URL
  dest = dest_path.format(symbol) # Add the curret symbol as the file name
  urllib.request.urlretrieve(url, dest)
  c+=1