2

I have a question about how to save files after I convert them from psd to jpg using python. Since I want to check every file, I used os.walk function. Here is my code. When I run this, I have this error.

FileNotFoundError: [Errno 2] No such file or directory: 'test02.psd'

The folder I want to save files in is in the same category as python file. But the psd file is in the subfolder somewhere.

How can I get over this?

from PIL import Image
import os


for path, dir, files in os.walk('.'):
    for file in files:
        if file.endswith('.psd'):
            print('The {} is being converted to jpg...'.format(file))
            i  = Image.open(file)
            fn, fext = os.path.splitext(file)
            try:
                i.save('jpgs/{}.jpg'.format(fn)) # I created a folder named 'jpgs' already.
            except Exception as e:
                print(e)
J.Shim
  • 71
  • 1
  • 5
  • Which line throws this error? –  Mar 22 '18 at 08:58
  • @Aran-Fey close, but not exactly the same. Your suggestion is about `os.listdir` – Jean-François Fabre Mar 22 '18 at 09:01
  • @Jean-FrançoisFabre The problem is the same, `listdir` or not. I can rewrite it to be our canonical dupe for `listdir` _and_ `os.walk` if you'd prefer. – Aran-Fey Mar 22 '18 at 09:04
  • Sorry to disagree, you'll have to find a better duplicate. `os.listdir` returns the file _names_, `os.walk` returns a triplet root+list of files+list of dirs for each dir. Not as easy to grasp. That plus the fact that user used current directory and hoped it would solve it magically. – Jean-François Fabre Mar 22 '18 at 09:06
  • a canonical about 2 different functions? that's a bit of a stretch. I don't like duplicates & users which answer duplicates knowing that the dupe exists just for rep. If I find a good one, I'll close. – Jean-François Fabre Mar 22 '18 at 09:07
  • @Jean-FrançoisFabre Is [this](https://stackoverflow.com/questions/34725117/python-existing-file-not-found-ioerror-errno-2-with-openpyxl) good enough? – Aran-Fey Mar 22 '18 at 09:20
  • @Aran-Fey absolutely not :) the title of this one is better IMHO (for my defence :)) – Jean-François Fabre Mar 22 '18 at 09:48

1 Answers1

2

os.walk walks recursively and in the lower directories, and loads the current dir of the file(s) in path. file is just the file name.

What would work with os.listdir (using current directory) or in the current directory (when path is .) doesn't work with os.walk. You have to prepend the root dir

i  = Image.open(os.path.join(path,file))
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219