gpt4 book ai didi

Python - 如何停止循环

转载 作者:太空宇宙 更新时间:2023-11-03 10:51:03 27 4
gpt4 key购买 nike

我有这个,它读取一个名为 source1.html、source2.html、source3.html 的文件,但是当它找不到下一个文件(因为它不存在)时,它会给我一个错误。可以有 x 数量的 sourceX.html,所以如果找不到下一个 sourcex.html 文件,我需要说些什么,停止循环。

Traceback (most recent call last): File "main.py", line 14, in file = open(filename, "r") IOError: [Errno 2] No such file or directory: 'source4.html

如何停止脚本寻找下一个源文件?

from bs4 import BeautifulSoup
import re
import os.path

n = 1
filename = "source" + str(n) + ".html"
savefile = open('OUTPUT.csv', 'w')

while os.path.isfile(filename):

strjpgs = "Extracted Layers: \n \n"
filename = "source" + str(n) + ".html"
n = n + 1
file = open(filename, "r")
soup = BeautifulSoup(file, "html.parser")
thedata = soup.find("div", class_="cplayer")
strdata = str(thedata)
DoRegEx = re.compile('/([^/]+)\.jpg')
jpgs = DoRegEx.findall(strdata)
strjpgs = strjpgs + "\n".join(jpgs) + "\n \n"
savefile.write(filename + '\n')
savefile.write(strjpgs)

print(filename)
print(strjpgs)

savefile.close()
print "done"

最佳答案

使用 try/exceptbreak

while os.path.isfile(filename):
try: # try to do this
# <your code>
except FileNotFoundError: # if this error occurs
break # exit the loop

您的代码当前无法运行的原因是您正在检查 while 循环中是否存在 previous 文件。不是下一个。因此你也可以这样做

 while True:
strjpgs = "Extracted Layers: \n \n"
filename = "source" + str(n) + ".html"
if not os.path.isfile(filename):
break
# <rest of your code>

关于Python - 如何停止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50289925/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com