简体   繁体   中英

How to open a random file from a directory in python?

I want to open a random file from a given directory. I tried this:

import os, random
random.choice(os.listdir("C:\\"))

but it's not working. I tried this on the other hand:

import os, random

random.choice([x for x in os.listdir("C:\\") if os.path.isfile(os.path.join("C:\\", x))])

It worked but it's only listing the files in the directory but not starting them. How do I start these files?

Your code will get the filename of random file, but you should open the file to view its contents. After the discussion in comments section, the file format is mp3 and can be played using the webbrowser module.

import os, random
import webbrowser
basedir = "C:\\"

file = random.choice([x for x in os.listdir(basedir) if os.path.isfile(os.path.join(basedir, x))])

print("Playing file {}...".format(file))
webbrowser.open(os.path.join(basedir, file))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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