I am building a script to download images from Bing using the downloader module in the bing_image_downloader library.
This is my code as it currently stands. It works if I set "force_replace" to False, but I want the output directory to be refreshed each time the script runs.
Current code:
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") as connection:
connection.starttls()
connection.login(user=sender_email, password=password)
connection.send_message(msg)
print("Email sent successfully")
The error I get when I run this script is:
"AttributeError: type object 'Path' has no attribute 'isdir'. Did you mean: 'is_dir'?"
I have then gone into the "downloader" module and looked at the "download" function.
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)
I modified the original if Path.isdir(image_dir)
image_dir = Path(output_dir).joinpath(query).absolute()
if force_replace:
if Path.isdir(image_dir):
shutil.rmtree(image_dir)
to if Path.is_dir(image_dir)
image_dir = Path(output_dir).joinpath(query).absolute()
if force_replace:
if Path.is_dir(image_dir):
shutil.rmtree(image_dir)
Once I did this modification the code ran perfectly the first time ("dataset2" folder not in files) but if I went to run it a second time I would get the following error.
EDIT: I have provided the entire traceback error message to enhance understanding. I have censored out any personal info of mine.
Traceback (most recent call last):
File "c:\Users\[censored]\OneDrive - [censored]\PC\Desktop\daily_motivational_quotes\test.py", line 14, in <module>
downloader.download(search_query, limit=30, timeout=60, output_dir="dataset2", force_replace=True)
File "C:\Users\[censored]\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\bing_image_downloader\downloader.py", line 25, in download
shutil.rmtree(image_dir)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2288.0_x64__qbz5n2kfra8p0\Lib\shutil.py", line 781, in rmtree
return _rmtree_unsafe(path, onexc)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2288.0_x64__qbz5n2kfra8p0\Lib\shutil.py", line 639, in _rmtree_unsafe
onexc(os.rmdir, path, err)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2288.0_x64__qbz5n2kfra8p0\Lib\shutil.py", line 637, in _rmtree_unsafe
os.rmdir(path)
PermissionError: [WinError 5] Access is denied: 'C:\\Users\\[censored]\\OneDrive - [censored]\\PC\\Desktop\\daily_motivational_quotes\\dataset2\\cute penguin'
I have been learning Python for a few months so please excuse anything I am yet to understand. Any idea as to what the issue could be?