Это мой код в его нынешнем виде. Это работает, если я устанавливаю для параметра Force_replace значение False, но я хочу, чтобы выходной каталог обновлялся каждый раз при запуске сценария.
Текущий код:
Код: Выделить всё
import smtplib
from email.message import EmailMessage
import os
from bing_image_downloader import downloader
import random
from dotenv import dotenv_values
import time
#Load environment variables
config = dotenv_values(".env")
#Downloading images from Bing with the specified search query
search_query = "cute penguin"
downloader.download(search_query, limit=30, timeout=60, output_dir="dataset2", force_replace=True)
time.sleep(5)
#Getting a random image
random_image = random.choice(os.listdir(f"dataset2/{search_query}"))
#Email Details
sender_email = config["sender_email"]
receiver_email = config["email"]
subject = "Test Email"
body = "This is a test email"
password = config['sender_password']
#Create Email Message
msg = EmailMessage()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = subject
msg.set_content(body)
#Path to the image file
image_path = f"dataset2/{search_query}/{random_image}"
#Read the image file
with open(image_path, "rb") as image_file:
image_data = image_file.read()
image_name = os.path.basename(image_path)
#Add image as attachment
msg.add_attachment(image_data, maintype="image", subtype="jpeg", filename=image_name)
with smtplib.SMTP("smtp.gmail.com") as connection:
connection.starttls()
connection.login(user=sender_email, password=password)
connection.send_message(msg)
print("Email sent successfully")
Код: Выделить всё
"AttributeError: type object 'Path' has no attribute 'isdir'. Did you mean: 'is_dir'?"
Код: Выделить всё
import os, sys
import shutil
from pathlib import Path
try:
from bing import Bing
except ImportError: # Python 3
from .bing import Bing
def download(query, limit=100, output_dir='dataset', adult_filter_off=True,
force_replace=False, timeout=60, filter="", verbose=True):
# engine = 'bing'
if adult_filter_off:
adult = 'off'
else:
adult = 'on'
image_dir = Path(output_dir).joinpath(query).absolute()
if force_replace:
if Path.isdir(image_dir):
shutil.rmtree(image_dir)
# check directory and create if necessary
try:
if not Path.is_dir(image_dir):
Path.mkdir(image_dir, parents=True)
except Exception as e:
print('[Error]Failed to create directory.', e)
sys.exit(1)
print("[%] Downloading Images to {}".format(str(image_dir.absolute())))
bing = Bing(query, limit, image_dir, adult, timeout, filter, verbose)
bing.run()
if __name__ == '__main__':
download('dog', output_dir="..\\Users\\cat", limit=10, timeout=1)
Код: Выделить всё
image_dir = Path(output_dir).joinpath(query).absolute()
if force_replace:
if Path.isdir(image_dir):
shutil.rmtree(image_dir)
Код: Выделить всё
image_dir = Path(output_dir).joinpath(query).absolute()
if force_replace:
if Path.is_dir(image_dir):
shutil.rmtree(image_dir)
Код: Выделить всё
PermissionError: [WinError 5] Access is denied
Подробнее здесь: https://stackoverflow.com/questions/793 ... replace-pa
Мобильная версия