Set default location to save file

Asked

Viewed 50 times

-1

I am creating a script in python to convert all the files of a folder into another format informed by the user, but I wanted to ask only once the location to save the files. I tried to use askdirectory() but it gives a strange error that the directory where the files are being the same where they will be saved even adding to different variables.

import glob
import img2pdf
from tkinter import Tk
from tkinter.filedialog import askdirectory


def img_to_pdf(arq, savefile):
    with open(f"{str(arq)[0:-4]}.pdf", "wb") as f:
        f.write(img2pdf.convert(arq))


def convert(filelocal, inpt, outpt, savefile):
    path = Path(str(filelocal))
    for arq in path.glob('*'):
        if arq.endswith(str(inpt)):
            if inpt == ".png" and outpt == ".pdf":
                img_to_pdf(arq, savefile)


def localfile():
    Tk().withdraw()
    filelocal = askdirectory()
    return filelocal


def filesave():
    Tk().withdraw()
    savefile = askdirectory()
    return savefile


if __name__ == '__main__':
    inpt = ".png"
    outpt = ".pdf"
    filelocal = localfile()
    savefile = filesave()
    convert(filelocal, inpt, outpt, savefile)

Any suggestions how I can fix this problem? Because the solutions I have found so far only help if it is to save a single file, so for each file inside the folder, it would ask again the location. What I want is to set a place to save by default.

1 answer

0

I believe I was not very clear with the example code, but I have already solved the problem. If someone has the same question, the way I did it was, instead of passing one by one the files to convert, the function gets a list with the path of all of them and the askdirectory function I open in the function itself that will convert, then I make a loop for to go converting file by file and moving to the destination folder.

Thus:

def img_to_pdf(arq):
    save_file = str(askdirectory(initialdir="/home"))
    for i in arq:
        fullname = str(i)[0:-4] + '.pdf'
        with open(fullname,"wb") as f:
            f.write(img2pdf.convert(str(i)))
        shutil.move(fullname, save_file)

for more details, the source code is all available and commented in English on my github repository: https://github.com/ThiagoA20/File-converter

Browser other questions tagged

You are not signed in. Login or sign up in order to post.