Home > Enterprise >  How to select single random file from each sub directory in python
How to select single random file from each sub directory in python

Time:04-15

I have a list of sub directories inside each directory , now I want to count the number of files from each sub category and select any one random file from each category and print them. The problem I am having is when i am creating a list of numbers to pick select any random number from that list and pick the number file from the sub category is not working.

n=list(range(0,100))
for dirpath, dirnames, filenames in os.walk('./Alphabets'):
    i=random.choice(n)
    for filename in [f for f in filenames][:random.choice(n)]:
        print(x,filename)

The problem with this code is when any random number is selected from the list, for example 16 number , then the output will be 16 random files. This fails my objective because if there are 20 number of sub directories then the output will be 20 random files, from sub directory one random file should be selected.

CodePudding user response:

just do this

for d, ds, fs in os.walk('./Alphabets'):
    if not fs: continue
    print(f"rd.choice(fs): {random.choice(fs)}")
  • Related