Upload every photo present in specific folder, without duplicates - python-3.x

I need help. After obtaining a list of photo names (.jpg) in a specific folder (chosen randomly from various folders), is there a way to upload every photo in that folder to a site, until they are finished? I would also like to avoid uploading duplicates.
So far, I have only managed to get a list of photos in a folder:
current_dir = os.getcwd()
folder = random.randint(1, 27)
img_path = current_dir + '\\' + 'Photo' + '\\' + str(folder)
img_dir = os.listdir(img_path)
img_list = []
for N in img_dir:
img_list.append(N)
At this point, I wanted to upload every single photo in the randomly selected folder using the send_keys() command, for example: driver.find_element(By.XPATH, "//input[#type='file']").send_keys(). But how can I do that? Thank you in advance for your help.

Related

Python Pillow library not saving files with same name in same location

Below is the code I am using to convert a binary data into image and then saving it
img = base64.b64decode(rec.image3)
img_conv = Image.open(io.BytesIO(img))
img_format = img_conv.format
img_conv.save('{}/{}'.format(path, rec.image_name), format(img_format))
There are 4 images with same code and I want to handle the scenario where if all the file names are same in the same location, it should force to save the 4 images even though it has duplicate name.
Any suggestion would be appreciated. Thanks.
Supposing that you want to keep each file under a different name: Append '_' to the original filename as long as a file with such a name exists in your directory.
from pathlib import Path
path_to_save = Path(path, rec.image_name)
while path_to_save.exists():
path_to_save = Path(str(path_to_save) + '_')
img_conv.save(path_to_save, format(img_format))

How to determine the file extension?

I was trying to copy an image with the path : userDATA\user1\profile_image, but unfortunaly, I don`t know the file extention, because the user can drop his own image, so that the suffix is sometimes different.
file_path = drop_image_instance.image_path # the path looks like this: C:\user\images\download1.png
copyfile(file_path, "userDATA\\" + username + "\\profile_image")
My question is, how can I find out, which suffix the file has, or how can i detect the ending in file_path?
For example:
def find_suffix(path):
file_ending = path[1]
return file_ending
Thanks for answers!

Image Comparison with a updating comparison image (PIL)

I need to compare the 1st image from a folder, deleting duplicates, until it finds one that doesn't match. Then it compares the new image with the rest of the picture, repeating the first process. I don't know if I'm forgetting something obvious but how to I set the new image as the comparison. Below is my first attempt at it, the idea that first_image for im1 would be updated after the loop. Any advice would be appreciated.
def add():
for image in files:
im1 = Image.open(path+ "/"+first_image).histogram() #the image to be compared too
im = Image.open(path+ "/" +image).histogram() #the image to be compared
if im == im1:
os.rename(path + "/" + file, path + "/delete")
else:
os.rename(path + "/" + file, path + "/save") ```
The answer was so simple, was overthinking it a lot. just defined the image before the for loop then have the for loop update it as necessary

Create folders dynamically and write csv files to that folders

I would like to read several input files from a folder, perform some transformations,create folders on the fly and write the csv to corresponding folders. The point here is I have the input path which is like
"Input files\P1_set1\Set1_Folder_1_File_1_Hour09.csv" - for a single patient (This file contains readings of patient (P1) at 9th hour)
Similarly, there are multiple files for each patient and each patient files are grouped under each folder as shown below
So, to read each file, I am using wildcard regex as shown below in code
I have already tried using the glob package and am able to read it successfully but am facing issue while creating the output folders and saving the files. I am parsing the file string as shown below
f = "Input files\P1_set1\Set1_Folder_1_File_1_Hour09.csv"
f[12:] = "P1_set1\Set1_Folder_1_File_1_Hour09.csv"
filenames = sorted(glob.glob('Input files\P*_set1\*.csv'))
for f in filenames:
print(f) #This will print the full path
print(f[12:]) # This print the folder structure along with filename
df_transform = pd.read_csv(f)
df_transform = df_transform.drop(['Format 10','Time','Hour'],axis=1)
df_transform.to_csv("Output\" + str(f[12:]),index=False)
I expect the output folder to have the csv files which are grouped by each patient under their respective folders. The screenshot below shows how the transformed files should be arranged in output folder (same structure as input folder). Please note that "Output" folder is already existing (it's easy to create one folder you know)
So to read files in a folder use os library then you can do
import os
folder_path = "path_to_your_folder"
dir = os.listdir(folder_path)
for x in dir:
df_transform = pd.read_csv(f)
df_transform = df_transform.drop(['Format 10','Time','Hour'],axis=1)
if os.path.isdir("/home/el"):
df_transform.to_csv("Output/" + str(f[12:]),index=False)
else:
os.makedirs(folder_path+"/")
df_transform.to_csv("Output/" + str(f[12:]),index=False)
Now instead of user f[12:] split the x in for loop like
file_name = x.split('/')[-1] #if you want filename.csv
Let me know if this is what you wanted

How to change where the output directory where the new images go

I have a small query I'm hoping someone can help me out within Python 3. I am resizing a dataset of 10000 images to all be 1000x1000 in dimension before I do any pytorch analysis with it. I just wanted to ask how I change my code to save the outgoing images to a new folder I have created ''train_resized'' instead of the same folder as the original files as it is doing now when I run. Thanks
# Testing dataset
from PIL import Image
import os, sys
path = (r'G:\My Drive\CATSVDOGS2.0\test1\\')
dirs = os.listdir( path )
def resize():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imResize = im.resize((1000,1000), Image.ANTIALIAS)
imResize.save(f + ' resized.jpg', 'JPEG', quality=90)
resize()
In your line
imResize.save(f + ' resized.jpg', 'JPEG', quality=90)
you're setting the path when using the variable f, as f uses the path variable you defined. A quick way to set the path is to do something like:
imResize.save('G:\\My Drive\\Path\\To\\Folder\\' + item + ' resized.jpg', 'JPEG', quality=90)
of course specify the path to be whatever you want. Untested as I don't have Python installed on my work machine, but that is the general gist.

Resources