Python Forum

Full Version: How to split name.jpg and get the string name
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
As a beginner, I have almost done what I want to do.

I can use python to resize photos, resize the excel table row heights, put photos in each row of column A. I can do that now.

But of course, I need the photos to match the names. Now I just need to match the photo with the name in column C.

I have a photo say 'fred.jpg' I want this photo in column 1 of the table. Somewhere in column C is the name 'fred'. (Actually all the names are Chinese.)

In this loop, let's say fred.jpg is the first filename

for filename in os.listdir(pathToFiles):
	if not (filename.endswith(fileEnding)):
		continue
TODO

1 For each filename which has the format 'name.jpg' get the string 'name'
2 Find that name in column C.
3 Get the row number of that name
4 put the photo in column A of that name row number

I'm not sure how to get the string name from name.jpg The rest I can do I think.
Next month I will get another 4 classes, about 160 students, I'm fed up doing this manually! Python to the rescue!
os.path.splitext

>>> import os
>>> f = 'fred.jpg'
>>> f
'fred.jpg'
>>> os.path.splitext(f)
('fred', '.jpg')
If your string is just name.jpg, you can simply split the string:
>>> name, ext = 'name.jpg'.split('.')
>>> name
'name'
If you're dealing with more complicated file paths, you should take a look at os.path or pathlib
Thanks, that did it! I used:

# put the pics in the excel file in column 1
for filename in os.listdir(pathToPhotos):
	if not (filename.endswith('.jpg')):
		continue
	for rowNum in range(beginRow, ws.max_row + 1):
		getName = filename.split('.')
		if (getName[0] == ws.cell(row=rowNum, column=col).value):
			print('found the name! Name is: %s ' % (getName[0]))
			print('Putting pic in row ' + str(rowNum))
			img = Image(pathToPhotos + filename)
			ws.add_image(img, 'A' + str(rowNum))
Which worked fine. However, other sheets in this excel file already had photos which I had manually inserted. Luckily, I saved the file as filename_copy.xlsx , because, when I looked, all the other photos for old classes were gone!! I do not know why!
I managed to copy the new class sheet with photos into the old excel file which saved the day.