遍历每个文件或文件夹,如果是文件夹,则递归调用print_directory_tree函数,并更新缩进字符串;如果是文件,则直接打印。 使用├──和└──来表示目录树的结构,其中├──表示当前项不是最后一个项,└──表示当前项是最后一个项。 通过这种方式,你可以轻松地打印出指定目录的目录树结构。
defprint_directory_tree(path,indentation):# 获取目录下的所有文件和子目录files=os.listdir(path)forfileinfiles:# 获取文件或子目录的绝对路径file_path=os.path.join(path,file)# 判断是否为目录ifos.path.isdir(file_path):# 输出目录名称,并增加缩进print(indentation+"|___"+file)# 递归调用自身,获取子...
importosdefprint_directory_tree(root_path,indent=""):""" 递归打印目录树 """ifnotos.path.isdir(root_path):returnfiles=os.listdir(root_path)files.sort()forfile_nameinfiles:file_path=os.path.join(root_path,file_name)ifos.path.isdir(file_path):print(f"{indent}├──{file_name}")print_...
directory=os.path.abspath("test")tree=Tree(f":open_file_folder:[link file://{directory}]{directory}",guide_style="bold bright_blue",)walk_directory(pathlib.Path(directory),tree)print(tree) 显示效果比Linux的tree命令更秀。不过这个脚本兼容性较差,Windows控制台并不支持显示图标之类的,导致会出现乱...
在该with块中,您将启动一个for循环,以将目录树图打印到提供的输出文件中。请注意,这print()也可以写入文件系统上的常规文件。为此,您只需要提供一个自定义file参数即可。 完成后DirectoryTree,您可以更新命令行界面以启用输出文件选项。回到cli.py并像这样修改它: ...
path.isdir(item_path): print(indent + '|-- ' + item) Display the tree of items with indent+ ' ') else: print(indent + '|-- ' + item) # 请将要展示目录树的起始路径替换为您想要的路径 start_path = '/directory/path' display_dir_tree(start_path) 展示结果 将start_path变量替换为您...
path.exists(root_directory): with open('tree.txt', 'w') as file: file.write(f"{os.path.basename(root_directory)}\n") print_tree(root_directory) print("文件树已保存到tree.txt中。") else: print("输入的路径不存在。") 这样就可以了!
# do something to this directory print("\t" * deep, dir) traverse_dir(path, deep + 1) if os.path.isfile(path): # do something to this file print("\t" * deep, "|--", dir) 执行traverse_dir("./") 后,遍历效果如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18...
insert(0, "```") tree.append("```") self._output_file = open( self._output_file, mode="w", encoding="UTF-8" ) with self._output_file as stream: for entry in tree: print(entry, file=stream) This update is almost a full reimplementation of DirectoryTree. First, you add a ...
os.rename(src, dst) 重命名file或者directory src到dst 如果dst是一个存在的directory, 将抛出OSError. 在Unix, 如果dst在存且是一个file, 如果用户有权限的话,它将被安静的替换. 操作将会失败在某些Unix 中如果src和dst在不同的文件系统中. 如果成功, 这命名操作将会是一个原子操作 (这是POSIX 需要). 在...