我正在尝试遍历目录中的所有目录并在那里找到所有 .html 文件。到目前为止,我有这段代码:
def find_path():
"""
:return: List
"""
paths = []
for filename in os.listdir(DIRECTORY):
if filename.endswith('.html'):
fname = os.path.join(DIRECTORY, filename)
with open(fname, 'r') as f:
soup = BeautifulSoup(f.read(), 'html.parser')
path = soup.select_one('#tree > li > span').contents[-1]
paths.append(path)
return paths
但它只有在所有 .html 文件都在一个目录中时才有效。我需要的是遍历该目录中的所有 .html 文件并保存它,但是对于该目录中的每个目录,还有我需要访问的 .html 文件。所以理想情况下,我需要在我的父目录中打开所有这些目录,并从 .html 文件中保存我需要的任何内容。有没有办法做到这一点?
谢谢!
您可以使用下面的示例片段 #1 或 #2 作品:
import os
path = "."
for (root, dirs, files) in os.walk(path, topdown=True):
for file in files:
if file.endswith(".html"):
print(root+"/"+file) #1
print(os.path.join(root+"/"+file)) #2
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句