Python Forum

Full Version: What is "KeyError: '刘洁.JPG'"
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to make a lot of student photos smaller, then paste them into an excel sheet. picSize is 300 pixel or 1"

I have almost got the resizing working, but I get this error:

Quote:Traceback (most recent call last):
File "<pyshell#107>", line 19, in <module>
im.save(resizedFilesDir, filename)
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 1669, in save
save_handler = SAVE[format.upper()]
KeyError: '刘洁.JPG'

Any tips please?

for filename in os.listdir(pathToFile):
	if not (filename.endswith('.png') or filename.endswith('.jpg')):
		continue
	im = Image.open(filename)
	width, height = im.size
	if width > picSize and height > picSize :
                # Calculate the new width and height to resize to.
		if width > height:
			height = int(picSize / width * height)
			width = picSize
		else:
			width = int(picSize / height * width)
			height = picSize
                        # Resize the image.
			print('Resizing %s...' % (filename))
			im = im.resize((width, height))
			print('changing image size...')
                        # Save changes.
			im.save(resizedFilesDir, filename)

Resizing 刘洁.jpg...
changing image size...
Traceback (most recent call last):
File "<pyshell#107>", line 19, in <module>
im.save(resizedFilesDir, filename)
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 1669, in save
save_handler = SAVE[format.upper()]
KeyError: '刘洁.JPG'
This key translates to 'Liu Jie .JPG' are there actually spaces in the name
and you may have to encode to the character set used.
SOLVED: the error is not with the character set. In the book "Automate the Boring Stuff" Al Sweigart has the code:

im.save(os.path.join('withLogo', filename))

which I took to be:

im.save(path, filename)

somehow that won't work, but:

im.save(path + filename)

works!! I don't know why and I am just a beginner. As long as it works, I'm happy!
im.save() only takes one parameter.  That's why the first doesn't work.

In the book, he used os.path.join() to combine the path with the filename.  What you're doing, by concatenating the two strings together, will only work if the path happens to end with a path separator already.