我有这个代码在这里为我工作:
import urllib3
http = urllib3.PoolManager()
location = 'Drive\\where-images-go\\'
N = 0
for x in range(0, 5000):
urls = ('http://00000.IMAGE_1_'+str(x)+'.jpg')
r = http.request('GET', urls)
Name = str(N+1)
N += 1
with open(location + 'image'+Name+'_image.jpg', 'wb') as img:
img.write(r.data)
这段代码将创建一个将str(x)从0计算到5000的url。但是我还想添加另一个计数器,每5000个计数器将计数1,上面的计数器会上升到这五个零的位置。例如:
import urllib3
http = urllib3.PoolManager()
location = 'Drive\\where-images-go\\'
N = 0
for x in range(0, 224999):
for every 5000 in x:
othercounter = oc
oc = oc +1
urls = ('http://'+str(oc)+'.IMAGE_1_'+str(x)+'.jpg')
r = http.request('GET', urls)
Name = str(N+1)
N += 1
with open(location + 'image'+Name+'_image.jpg', 'wb') as img:
img.write(r.data)
因此,每当str(x)达到5000时,oc(其他计数器)将上升1.由于第二个示例代码的范围是(0,224999),oc计数器将是44,最后一个url将是'http://00044.IMAGE_1_224999.jpg'。第一张图片将是'http://00000.IMAGE_1_1.jpg'。
如何解决这个问题呢?
你可以使用mod %
来打印每5000个,我已经指出了你应该做的其他事情来实现你的目标:
oc
应初始化为-1
,因为你想从0
开始oc
保持5宽度与前缀0
,像00044
,所以你应该在这里使用rjust
:str(oc).rjust(5, '0')
0
没有必要range(0, 224999)
import urllib3
http = urllib3.PoolManager()
location = 'Drive\\where-images-go\\'
N = 0
oc = -1
for x in range(224999):
N += 1
if x % 5000 == 0:
oc += 1
urls = ('http://' + str(oc).rjust(5, '0') + '.IMAGE_1_' + str(N) + '.jpg')
r = http.request('GET', urls)
with open(location + 'image'+str(N)+'_image.jpg', 'wb') as img:
img.write(r.data)
# test code, need to remove
# the first
if x == 0:
print('first url: {}'.format(urls))
# the last
if x == 224998:
print('last url: {}'.format(urls))
产量
first url: http://00000.IMAGE_1_1.jpg
last url: http://00044.IMAGE_1_224999.jpg
希望对您有所帮助,并在您有其他问题时发表评论。 :)
如果我理解你需要什么,你需要检查当前的数字是否可以被你需要的间隔整除(在这种情况下,5000)。
另请注意,通过将范围限制设置为5000,您的第一个计数器最多只能运行4999。
other_counter = 0
for x in range(0, 15_001): # Runs from 0 to 15000 included.
if x % 5000 == 0: # Results in True every time a multiple of 5000 is reached.
other_counter += 1