I have to display a random image from a folder using Python. I've tried
import random, os
random.choice([x for x in os.listdir("path")if os.path.isfile(x)])
but it's not working for me (it gives Windows Error: wrong directory syntax, even though I've just copied and paste).
Which could be the problem...
You need to specify correct relative path:
random.choice([x for x in os.listdir("path")
if os.path.isfile(os.path.join("path", x))])
Otherwise, the code will try to find the files (image.jpg
) in the current directory instead of the "path"
directory (path\image.jpg
).
UPDATE
Specify the path correctly. Especially escape backslashes or use r'raw string literal'
. Otherwise \..
is interpreted as a escape sequence.
import random, os
path = r"C:\Users\G\Desktop\scientific-programming-2014-master\scientific-programming-2014-master\homework\assignment_3\cifar-10-python\cifar-10-batches-py"
random_filename = random.choice([
x for x in os.listdir(path)
if os.path.isfile(os.path.join(path, x))
])
print(random_filename)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With