【问题标题】:cannot open resource: OS Error无法打开资源:操作系统错误
【发布时间】:2018-08-23 06:27:22
【问题描述】:

OSError Traceback(最近调用 最后)在()中

21 绘制 = PIL.ImageDraw.Draw(img) 22 打印(os.path.join(路径,文件名)) ---> 23 draw.font = PIL.ImageFont.truetype((os.path.join(path, filename))+ '.ttf', 44) 24 t2 = get_display(t1) 25 w, h = draw.textsize(t2)

()

OSError: 无法打开资源

我在关注PIL 时遇到此错误,或者我犯了一些错误。它只显示第一个文件路径,然后出现此错误。

unicode_text = u"\u0627"
list_of_letters = list (unicode_text) 
folder = 1 
n=1 
i=0
for i in range(0,158):
    path = r"E:\Dummy\fonts"
    dirs = os.listdir( path )
    for files in dirs:
        char = u''.join(list_of_letters) 
        t1 = arabic_reshaper.reshape(char) 
        W,H= (100, 100)
        img= PIL.Image.new('RGBA', (W, H), (255, 255, 255),)
        draw = PIL.ImageDraw.Draw(img)   
        print(os.path.join(path, filename))
        draw.font = PIL.ImageFont.truetype((os.path.join(path, filename)), 44)
        t2 = get_display(t1) 
        w, h = draw.textsize(t2)
        draw.text(((W-w)/2,(H-h)/2),t2, fill="#000000")
        path = 'E:\Dummy\sam\\'+ str(folder)
        if not os.path.exists(path):
            os.makedirs(path)
        img.save(path + '\\' + char+'.png', "PNG")
        folder+=1
            #i+=1

【问题讨论】:

    标签: python python-3.x for-loop python-imaging-library os.walk


    【解决方案1】:

    从您的回答中,程序失败的地方不是很清楚。它抱怨无法打开文件。这条线在我看来很可疑:

    path = 'E:\Dummy\sam\\'+ str(folder)
    

    我建议您永远不要手动将路径与反斜杠连接,而是始终使用 Python 标准库来为您执行此操作。例如,您不需要关心转义某些字符。

    dir_path = os.path.join('E:', 'Dummy', 'sam', str(folder))
    file_name = '{}.png'.format(char)
    file_path = os.path.join(dir_path, file_name)
    

    如果您不在循环内的文件夹中添加 1,而是使用内置函数 enumerate,则可以对代码进行另一项改进:

    for folder_index, file in enumerate(dirs, start=1):
        # Do your thing here
        # The variable folder_index is incremented automatically.
    

    【讨论】:

      猜你喜欢
      • 2011-09-14
      • 2011-04-26
      • 1970-01-01
      • 2010-09-20
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多