Home > Back-end >  How to turn a tuple/list into a filename?
How to turn a tuple/list into a filename?

Time:01-25

I have a list that takes some parameters from an image. And I need to save this image with this parameters on its name. I am calling it a list, but maybe it can be another thing, I am having trouble on identifying what type it is. On error box it's calling it "tuple".

It takes the filename of image, and all parameters from my code, then, turns each into string.

list = str(filename), str(cci[i]), str(gamma[j]), str(alfa[m]), str(beta[n]), "{:.4f}".format(uci), "{:.4f}".format(uiq)

When I print the list, this is what appears:

('GOPR0395.JPG', '0.8', '0.6', '0.4', '0.4', '5.8829', '3.5720')

And that's what I need in the new image I am going to save. I need this whole thing, separated. And i only know how to save it making its filename a string, like this:

cv2.imwrite(f'{DIR_results}{str(filename)}', image) 

I wish the filename for "image" was

GOPR0395_08_06_04_04_53829_35720.JPG

Any tips? Thank you

CodePudding user response:

Try the following code:

x = ('GOPR0395.JPG', '0.8', '0.6', '0.4', '0.4', '5.8829', '3.5720')
my_str = '_'.join(x) .replace('.', '').replace('JPG', "")   '.jpg'

CodePudding user response:

I would recommend doing something like this: first you replace all your commas with a Then you add '_' between every string you add. You can use .replace('a','b') to get rid of the dots and the ".JPG". At the end your code should look something like this:

filename = (str('GOPR0395.JPG').replace(".JPG","")   "_"  str('0.8') "_"   str('0.6')  "_"  str('0.4') "_"   str('0.4')  "_"  str('5.8829')  "_"  str('3.5720')).replace('.','')   ".JPG"

be aware that I replaced all you variables with the input they represent because I dont know what they contain.

CodePudding user response:

Using the tuple example above you could split the first element on the . to separate the filename from the extension before joining (keeping the .extn outside the replace function). This would allow for images other than just JPG's.

x = ('GOPR0395.JPG', '0.8', '0.6', '0.4', '0.4', '5.8829', '3.5720')
filename =  '_'.join(((splits:=x[0].split("."))[0], *(x[1:]))).replace('.','')   f'.{splits[1]}'
print(filename) # GOPR0395_08_06_04_04_58829_35720.JPG
  • Related