This question already has an answer here:
Python: existing file not found (IOError: [Errno 2]) when using os.walk
                                
                                    (1个答案)
                                
                        
                                去年关闭。
            
                    
我对使用python将文件从psd转换为jpg后如何保存文件有疑问。由于我想检查每个文件,因此我使用了os.walk函数。这是我的代码。
运行此命令时,出现此错误。

FileNotFoundError:[错误2]没有这样的文件或目录:'test02.psd'

我要在其中保存文件的文件夹与python文件属于同一类别。
但是psd文件位于子文件夹中的某个位置。

我该如何克服?

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)

最佳答案

os.walk递归地走到较低目录中,并在path中加载文件的当前目录。 file只是文件名。

os.listdir(使用当前目录)或当前目录(当path.时)适用于os.walk。您必须在根目录之前

i  = Image.open(os.path.join(path,file))

关于python - 如何转换和保存文件(os.walk),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49424274/

10-14 18:25
查看更多