简体   繁体   English

如何在 python 中创建树?

[英]How to create a tree in python?

I have a folder of 100 html files that I am trying to create a tree out of name page1 - page100.我有一个包含 100 个 html 文件的文件夹,我正在尝试创建一个名称为 page1 - page100 的树。 Each page has a hyperlink in it that opens up another page.每个页面都有一个超链接,可以打开另一个页面。 I am trying to get it to where the program reads the root node(page1.html) reads its hyperlinks and creates children based off those links, and then repeats this for the rest of the nodes until the tree is complete.我试图让它到程序读取根节点的位置(page1.html)读取其超链接并根据这些链接创建子节点,然后对节点的 rest 重复此操作,直到树完成。 What is the best way to go about this using the hyperlinks? go 使用超链接的最佳方法是什么? Here is my code so far.到目前为止,这是我的代码。

    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()

You can use os.walk to iterate over all subdirectories:您可以使用 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

Please ask if something is unclear.请询问是否有不清楚的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM