[英]How to create a tree in python?
我有一個包含 100 個 html 文件的文件夾,我正在嘗試創建一個名稱為 page1 - page100 的樹。 每個頁面都有一個超鏈接,可以打開另一個頁面。 我試圖讓它到程序讀取根節點的位置(page1.html)讀取其超鏈接並根據這些鏈接創建子節點,然后對節點的 rest 重復此操作,直到樹完成。 go 使用超鏈接的最佳方法是什么? 到目前為止,這是我的代碼。
import os
from math import*
from os.path import isfile, join
entries = os.listdir("C:/Users/deonh/Downloads/intranets/intranet1") #This reads the directory
onlyfiles = [f for f in entries if isfile(join("C:/Users/deonh/Downloads/intranets/intranet1", f))] #This took all the webpages in the directory and put them into a list.
print(onlyfiles)
web = open("C:/Users/deonh/Downloads/intranets/intranet1" + "/" + onlyfiles[0]) # This will tell us if the webpage is readable or not
print(web.readable()) # This tells if the file is readable
print(web.readlines()) #This reads the content of the file
web.close()
您可以使用 os.walk 遍歷所有子目錄:
import os
path = 'C:/Users/deonh/Downloads/intranets/intranet1'
entries = []
onlyfiles = []
for directory, _, files in os.walk(path): # second value would be subdirectries but we don't need them because we iterate over all directories
entries.append(directory)
for file in files:
onlyfiles.append('{}/{}'.format(directory, file)) #
if os.access(onlyfiles[0], os.R_OK): # This will tell us if the webpage is readable or not
with open(onlyfiles[0]) as file: # file is closing automatically
print(file.readlines())
print(onlyfiles[0], os.R_OK) # This tells if the file is readable
print(onlyfiles) # This reads the content of the file
請詢問是否有不清楚的地方。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.