Random Walk Directory Traversal Function

  • Share this:

Code introduction


The function starts from a given directory and performs a random walk for a certain number of steps, returning a list of paths in the process.


Technology Stack : os, sys, time, json, re, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import sys
import time
import json
import re
import random

def random_walk(start_dir, max_steps=10):
    """
    随机漫步函数,从一个目录开始,随机漫步一定步数
    """
    path = [start_dir]
    for _ in range(max_steps):
        try:
            entries = os.listdir(path[-1])
            next_entry = random.choice(entries)
            path.append(os.path.join(path[-1], next_entry))
        except (FileNotFoundError, IndexError):
            break
    return path