这可能吗?我想一次在我的文件中打印行(以批量发送到API)。但是当我到达最后几行时,他们从不打印,因为少于5行,从不触发我的if语句打印。所以我认为解决这个问题的一种方法是在循环关闭时打印剩余的行。
目前的代码很乱并且多余,但这就是这个想法:
urls = []
urls_csv = ""
counter = 0
with open(urls_file) as f:
for line in f:
# Keep track of the lines we've went through
counter = counter + 1
# If we have 5 urls in our list it's time to send them to the API call
if counter > 5:
counter = 0
urls_csv = ",".join(urls) # turn the python list into a string csv list
do_api(urls_csv) # put them to work
urls = [] # reset the value so we don't send the same urls next time
urls_csv = "" # reset the value so we don't send the same urls next time
# Else append to the url list
else:
urls.append(line.strip))
另外 - 一般来说,有没有更好的方法来解决这个问题?
答案 0 :(得分:2)
您可以使用itertools
grouper recipe将它们分组为5行。
import itertools
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
with open(...) as f:
for group in grouper(f, 5, fillvalue=""):
do_api(",".join([g.strip() for g in group if g]))
答案 1 :(得分:1)
您如何看待
urls = []
with open(urls_file) as f:
while True:
try:
for i in range(5):
urls.append(next(f).rstrip())
print(urls) # i.e. you have the list of urls, now use it/put it to work
urls = []
except StopIteration:
print(urls)
break
输入文件
line1
line2
line3
line4
line5
line6
line7
它产生
['line1', 'line2', 'line3', 'line4', 'line5']
['line6', 'line7']