Jump to content

melhorar script


PsySc0rpi0n

Recommended Posts

Boas.

Estou a tentar fazer um programa que recebe dois paths, lê as imagens que estão no primeiro path, abre-as, depois converte-as para 'png' e salva-as no segundo path.

Epá, fiz isto mas obviamente que isto está à pedreiro e não consegui usar o Pathlib devidamente. O que é que preciso mudar para isto não ficar assim tão à pedreiro?

Para já nem liguei ao facto de eu verificar os argumentos passados depois de usar o primeiro argumento... Agora quero é perceber como usar o Pathlib para guardar as imagens numa nova pasta.

import sys
from pathlib import Path
from PIL import Image

# grab first and second argument
# check if new/ exists, if not, create it
# loop through the folder and convert to png
# save to the new folder

def proc_args():
    """Process arguments from command line"""
    if len(sys.argv) < 3:
        print('Not enough parameters!')
        exit(-1)
    else:
        newpath = Path(sys.argv[2])
        try:
            newpath.mkdir(parents=True, exist_ok=False)
        except FileExistsError:
            print(f'{newpath} already exists!')
        except IOError as ioerr:
            print(f'{ioerr}: {newpath} could not be created')

    return newpath

def conv_imgs(pold_p, pnew_p):
    """Loop over files in folder"""
    for item in Path(pold_p).rglob('*.jpg'):
        img = Image.open(item)
        noext = item.with_suffix('')
        newext = noext.with_suffix('.png.png')
        tmp = Path(newext).stem
        print(tmp)
        img.save(Path(pnew_p).joinpath(tmp), 'png')

def main():
    """Main Function"""
    old_path = Path(sys.argv[1])
    new_path = proc_args()
    conv_imgs(old_path, new_path)

if __name__ == '__main__':
    main()

Obrigado

Kurt Cobain - Grunge misses you

Nissan GT-R - beast killer

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.