Search code examples
pythonimagepython-imaging-library

Cannot save an image in Python


I am making a console recorder in Python. But, when it tries to save 60.png in the FRAMES directory, It fails with error. Here's my code:

import os
from PIL import Image, ImageDraw
c = 1
def save():
    global c
    m = Image.new("RGB",(400,200),"#004c66")
    draw = ImageDraw.Draw(m)
    draw.text((5,5),text=output,fill=(255,255,255))
    with open(f"FRAMES/{c}.png","a+b") as fp:
        m.save(fp,"PNG")
    c+=1
output = 'Welcome to movieconsole!\nVersion: 0.1\n'
save()
with open('commands.txt') as fp:
  for i in fp.read().splitlines():
    if len(os.getcwd()) < 30:
        output += os.getcwd() + '$ '
    else:
        output += os.getcwd()[0:30] + '...$ '
    save()
    for l in i:
        output += l
        save()
    output += '\n'
    a = os.popen(i)
    for p in a.read().splitlines():
        output+=p+"\n"
        save()
        if len(output.splitlines()) > 12:
            output = '\n'.join(output.splitlines()[1::])
    if i[0:2] == 'cd':
        os.chdir(' '.join(i.split()[1::]))
    if len(output.splitlines()) > 12:
        output = '\n'.join(output.splitlines()[1::])
print(output)

And the error is: FileNotFoundError: [Errno 2] No such file or directory: 'FRAMES/60.png'


Solution

  • I think the problem is that you change directories whilst your program is running (in response to cd as input). Then when you try to write in a subdirectory called FRAMES it is no longer there.

    I would suggest you use Pathlib (which is part of the standard library and doesn't need installing) and create an absolute path to your output directory at program startup, then use that when constructing the output filename:

    from pathlib import Path
    
    # Near start of code... create output dir and save absolute path
    out = Path('FRAMES').absolute()
    out.mkdir(exist_ok = True)
    

    Then, later on, when you want to write frame 60:

    i = 60
    filepath = out / f'{i}.png'
    image.save(str(filepath))
    

    Note that an absolute path is one that begins with a slash and isn't affected by your changing directory. In contrast, a relative path is expressed relative to the current working directory, so it depends where you currently are in the filesystem.