I wrote the code and now I have problem that the code finde only the first value (for example only img, we have img2 too, but it went to another picture) and copy only one, but we have 2 possibilities.
for i in df_list:
img = (filepath + i + ".jpg")
img2 = (filepath + i + "-1" + ".jpg")
img3 = (filepath + i + "-2" ".jpg")
img4 = (filepath + i + "-3" + ".jpg")
img5 = (filepath + i + "-4" + ".jpg")
img6 = (filepath + i + " -5" + ".jpg")
try:
shutil.copy(img, newpath, follow_symlinks=True)
except:
try:
shutil.copy(img6, newpath, follow_symlinks=True)
except:
try:
shutil.copy(img2, newpath, follow_symlinks=True)
except:
try:
shutil.copy(img3, newpath, follow_symlinks=True)
except:
try:
shutil.copy(img4, newpath, follow_symlinks=True)
except:
try:
shutil.copy(img5, newpath, follow_symlinks=True)
except:
with open("C:/Users/"+user+"/Desktop/J/"+datum+"/"+"Napake.txt", "a") as text_file:
print("Slika za ident {} ne obstaja.\n".format(i), file=text_file)
I neeed help, thank you for answers.
Rather than copying the try,except you can loop over the filenumbers and try copy each file. and print an error if there is an exception.
save_path = "C:/Users/" + user + "/Desktop/J/" + datum + "/" + "Napake.txt"
for folder in df_list:
for index in range(6):
if index == 0:
img = filepath + folder + ".jpg"
else:
img = f"{filepath}{folder}-{index}.jpg"
try:
shutil.copy(img6, newpath, follow_symlinks=True)
with open(save_path, "a") as text_file:
text_file.write(f"Slika za ident {folder}-{i} ne obstaja.\n")
except Exception as e:
print('could not copy file')
print(e)
I would also recommend having a look at this answer to see how to copy all files in a directory.
Related
I am sending an extracted list with xpath but it doesn't work with xpath
it works like this URL1
url = ['http://images/productos/on-line/items/large/nb/de/nbdell1tc73.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_1.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_2.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_3.jpg'
]
it does not work URL2
url = sel.xpath('//section[#class="product-images js-product-images-container"]//img/#src')
result url.path
'url': ['http://images/productos/on-line/items/large/nb/de/nbdell1tc73.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_1.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_2.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_3.jpg'],
this code recepte the url
i = 0
for url22 in url:
try:
imagen_content = requests.get(url22).content
image_file = io.BytesIO(imagen_content)
imagen = Image.open(image_file).convert('RGB')
path = './imagenes/' + '_' + str(i) + '.jpg'
with open(path, 'wb')as f:
imagen.save(f, "JPEG", quality=85)
except Exception as ex:
print(ex)
print("ERROR")
i += 1
With the first url it works, with the second one it doesn't.
How do I make it work with url2?
it turned out, I need to put url.get () url22.get()
i = 0
for url22 in url:
try:
imagen_content = requests.get(url22.get()).content
image_file = io.BytesIO(imagen_content)
imagen = Image.open(image_file).convert('RGB')
path = './imagenes/' + '_' + str(i) + '.jpg'
with open(path, 'wb')as f:
imagen.save(f, "JPEG", quality=85)
except Exception as ex:
print(ex)
print("ERROR")
i += 1
I have a program which has a loop in it.
In this loop I load images from a file.
But there are some not usable images, that I don`t want to sort by hand.
I have this code:
img = Image.open("downloads/parrot/" + pictures[i])
img = img.resize((150,150))
img.save("Validation/parrot/" + "picture" + str(i) + ".png")
i = i + 1
I tried to use the try except method, but it always stopped the program.
Is there any way to use an if loop, like "if imageisuseful() = false:"?
Or do you may have any other Ideas?
Thank you for your help.
If you don't want your try / except to stop your code, you can pass :
try:
img = Image.open("downloads/parrot/" + pictures[i])
img = img.resize((150,150))
img.save("Validation/parrot/" + "picture" + str(i) + ".png")
i = i + 1
except:
pass # pictures[i] raised an exception here
Depending on where the error is happening (either at the open or the resize) you might need to move things around:
img = Image.open("downloads/parrot/" + pictures[i])
try:
img = img.resize((150,150))
img.save("Validation/parrot/" + "picture" + str(i) + ".png")
i = i + 1
except:
print("FILE {} DOESN'T WORK".format(pictures[i]))
I have some code that I wrote that downloads images from a website. The way that it currently works it needs to guess what the file extension will be for the url it will be downloading from. The block of code that does that looks like this:
for imageLink in imageLinks:
try:
urllib.request.urlretrieve(imageLink + ".png", str(threadName) + "/" + str(count) + ".png")
except:
try:
urllib.request.urlretrieve(imageLink + ".jpg",str(threadName) + "/" + str(count) + ".png")
except:
try:
urllib.request.urlretrieve(imageLink + ".gif",str(threadName) + "/" + str(count) + ".gif")
except:
urllib.request.urlretrieve(imageLink + ".webm",str(threadName) + "/" + str(count) + ".webm")
As it stands the code is relying on a fail in order to try something else.
I wanted to know if their is a way to have this functionality but to basically just look better. These methods will give identical errors if they fail so I want to just go through them sequentially until one works
for ext in ('.png', '.jpg', '.gif', '.webm'):
try:
urllib.request.urlretrieve(imageLink + ext, str(threadName) + "/" + str(count) + ext)
break
except:
pass
You can use a try/except block inside a function and return None if the control goes to the except statement. You can optimize the for loop according to your own needs. One example is here:
def get_url(link1, link2):
try:
requestData = urllib.request.urlretrieve(link1, link2)
except:
return None
return requestData
for imageLink in imageLinks:
data = urllib.request.urlretrieve(imageLink + ".png", str(threadName) + "/" + str(count) + ".png")
if data == None:
data = urllib.request.urlretrieve(imageLink + ".jpg",str(threadName) + "/" + str(count) + ".png")
if data == None:
data = urllib.request.urlretrieve(imageLink + ".gif",str(threadName) + "/" + str(count) + ".gif")
if data == None:
urllib.request.urlretrieve(imageLink + ".webm",str(threadName) + "/" + str(count) + ".webm")
how to download the image from google and rename the image with keywords at the same time when using google-images-download? While using this package, the name is generated from the Image URL
what I except is that the image can be named with the Item name
Could anyone help me ?
here is code:
from google_images_download import google_images_download
response = google_images_download.googleimagesdownload()
arguments = {"keywords":"cat, dog, pig", "limit":1, "print_urls":True, "image_directory":'home1', "size":"large"}
absolute_image_paths = response.download(arguments)
you need to override the methods in google_images_download including: download_image, _get_all_items, download. _get_all_items and download need to post download_image
# Download Images
def download_image(self,image_url,image_format,main_directory,dir_name,count,print_urls,socket_timeout,prefix,print_size,no_numbering,search_term):
if print_urls:
print("Image URL: " + image_url)
try:
req = Request(image_url, headers={
"User-Agent": "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"})
try:
# timeout time to download an image
if socket_timeout:
timeout = float(socket_timeout)
else:
timeout = 10
response = urlopen(req, None, timeout)
data = response.read()
response.close()
# keep everything after the last '/'
# for keyword in keywords.split(','):
# image_name = str(keyword)
# print(image_name)
image_name = search_term + "." + "jpeg"
print(image_name,'XXXxXXXXx')
# image_name = str(image_url[(image_url.rfind('/')) + 1:])
# image_name = image_name.lower()
# if no extension then add it
# remove everything after the image name
# if image_format == "":
# image_name = image_name + "." + "jpg"
# elif image_format == "jpeg":
# image_name = image_name[:image_name.find(image_format) + 4]
# else:
# image_name = image_name[:image_name.find(image_format) + 3]
# prefix name in image
if prefix:
prefix = prefix + " "
else:
prefix = ''
# if no_numbering:
path = main_directory + "/" + dir_name + "/" + prefix + image_name
# else:
# path = main_directory + "/" + dir_name + "/" + prefix + str(count) + ". " + image_name
print(path)
try:
output_file = open(path, 'wb')
output_file.write(data)
output_file.close()
absolute_path = os.path.abspath(path)
except OSError as e:
download_status = 'fail'
download_message = "OSError on an image...trying next one..." + " Error: " + str(e)
return_image_name = ''
absolute_path = ''
#return image name back to calling method to use it for thumbnail downloads
download_status = 'success'
download_message = "Completed Image ====> " + prefix + str(count) + ". " + image_name
return_image_name = prefix + str(count) + ". " + image_name
# image size parameter
if print_size:
print("Image Size: " + str(self.file_size(path)))
except UnicodeEncodeError as e:
download_status = 'fail'
download_message = "UnicodeEncodeError on an image...trying next one..." + " Error: " + str(e)
return_image_name = ''
absolute_path = ''
except URLError as e:
download_status = 'fail'
download_message = "URLError on an image...trying next one..." + " Error: " + str(e)
return_image_name = ''
absolute_path = ''
except HTTPError as e: # If there is any HTTPError
download_status = 'fail'
download_message = "HTTPError on an image...trying next one..." + " Error: " + str(e)
return_image_name = ''
absolute_path = ''
except URLError as e:
download_status = 'fail'
download_message = "URLError on an image...trying next one..." + " Error: " + str(e)
return_image_name = ''
absolute_path = ''
except ssl.CertificateError as e:
download_status = 'fail'
download_message = "CertificateError on an image...trying next one..." + " Error: " + str(e)
return_image_name = ''
absolute_path = ''
except IOError as e: # If there is any IOError
download_status = 'fail'
download_message = "IOError on an image...trying next one..." + " Error: " + str(e)
return_image_name = ''
absolute_path = ''
except IncompleteRead as e:
download_status = 'fail'
download_message = "IncompleteReadError on an image...trying next one..." + " Error: " + str(e)
return_image_name = ''
absolute_path = ''
return download_status,download_message,return_image_name,absolute_path
I am trying to copy a files from different folders under a path to my usb drive.
So my source directory structure looks like this
/user/arun/Music/Songs/
under this I have different sub directories
Songs_1
Songs_2
Songs_3
the target folder is under anyone of these Songs directory
Songs_1/Kid Rock/All summer long.mp3
Songs_2/Linkin Park/In the end.mp3
Now I am constructing my src_dir in a try/except way like this.
for album,song in song_database.iteritems():
for s in song:
try:
src_dir_1 = src_dir + "/" + "Songs_1" + "/" + album + "/" + s + ".mp3"
shutil.copy2(src_dir_1,dest_dir
print src_dir_1
except IOError:
pass
try:
src_dir_1 = src_dir + "/" + "Songs_2" + "/" + album + "/" + s + ".mp3"
shutil.copy2(src_dir_1,dest_dir)
print src_dir_1
except IOError:
pass
try:
src_dir_1 = src_dir + "/" + "Songs_3" + "/" + album + "/" + s + ".mp3"
shutil.copy2(src_dir_1,dest_dir)
print src_dir_1
except IOError:
pass
try:
src_dir_1 = src_dir + "/" + "Songs_4" + "/" + album + "/" + s + ".mp3"
shutil.copy2(src_dir_1,dest_dir)
print src_dir_1
except IOError:
pass
Is there a better way to do this ?
Seems like a loop would be better:
for album,song in song_database.iteritems():
for s in song:
for sdir in 'Songs_1', 'Songs_2', 'Songs_3':
try:
src_dir_1 = src_dir + "/" + sdir + "/" + album + "/" + s + ".mp3"
shutil.copy2(src_dir_1,dest_dir)
print src_dir_1
except IOError:
pass
And, perhaps you would want to add a break statement if you succeed in copying the source to the destination...
As a side note, you might want to use os.path.join instead:
src_dir_1 = os.path.join(src_dir, sdir, album, s + ".mp3")