N
N
nazlanmak2021-02-24 02:21:54
Bots
nazlanmak, 2021-02-24 02:21:54

How to output a random image from a file?

We need the code to send a random photo from the directory.

Used two methods, settled on the error "Syntax error in file name, folder name or volume label: ..."

DIR = 'D:\Python\telegramtest\photos'
photo = open(os.path.join(DIR, random. choice(os.listdir(DIR))))
bot.send_photo(message.chat.id, photo)

path = r'D:\Python\telegramtest\photos'
photo = random.choice([
x for x in os.listdir (path)
if os.path.isfile(os.path.join(path, x))
])
bot.send_photo(message.chat.id, photo)

60358dd8d55b5997770671.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Karbivnichy, 2021-02-24
@hottabxp

No need to take on bots without knowing the basics of Python!
And on business, at first without bot receive the list of images from a folder. Next, get a random element from the resulting list. Well, then you can connect the bot.

S
shurshur, 2021-02-24
@shurshur

In python (as in many other programming languages), the \ character in string values ​​is used for escaping and for special characters. For example, \t is a tab, \n is a line feed. Therefore, using \ in strings is not so easy. You must either prefix the string with an r to disable this behavior (r'c:\telegram'), or escape the slashes: ('c:\\telegram').

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question