Choosing a random file from a directory (with a large number of files) in Python

前端 未结 5 517
南笙
南笙 2021-02-07 20:58

I have a directory with a large number of files (~1mil). I need to choose a random file from this directory. Since there are so many files, os.listdir naturally tak

5条回答
  •  不思量自难忘°
    2021-02-07 21:28

    try this, (here is very fast with 50K files...)

    import glob
    import random
    
    list = glob.glob("*/*.*")
    print list[random.randrange(0,list.__len__())]
    

提交回复
热议问题