3
I’m trying to create a code that reads a directory with pdf files and creates 2 zipped files containing these pdf, in my code, I only managed to play all pdf in a single zipped file, my question is how to create the two.
Code:
class zipar_pdf:
def __init__(self, diretorio, nome):
self.diretorio = diretorio
self.nome = nome
def zipar(self):
#Criando arquivo zip com os pdf
with zipfile.ZipFile(self.nome, "w") as oZip:
print('Buscando arquivos...\n')
for caminho, _ , arquivos in os.walk(self.diretorio):
print(f'Compactando arquivos em {self.nome}...\n')
for arquivo in arquivos:
caminhoCompleto = os.path.join(caminho, arquivo)
if arquivo.startswith("test"):
oZip.write(caminhoCompleto, basename(caminhoCompleto))
PDF = zipar_pdf(r'exemplo_diretorio', 'arquivos.zip')
PDF.zipar()
In the directory has 6 pdf, with the name Test1.pdf, up to test6.pdf, it is possible to put up the test3 in a zipped file and then the rest in another?
Thanks for the help! About using classes, the reason is that I’m learning about this subject and I thought about applying, I’m new in the programming area, I made another version only with a function that was giving the same result
– Vitor Xavier
@Vitorxavier If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. Don’t forget that you can also vote in response, if it has found it useful.
– hkotsubo
One question, in this function, is taking the test.pdf files by the number that comes along in front of it, has some function that would put the files inside the . zip by quantity and not by name?
– Vitor Xavier
@Vitorxavier I don’t know, probably you will have to count manually (maybe use a counter in the loop, for example). Or you take the list of all the files and then iterate by parts. Ex:
arquivos = list(Path(diretorio).glob('*.pdf'))
to have a list of all the PDF’s, and then takearquivos[0:10]
for the first 10 (from zero to 9), thenarquivos[10:20]
to catch from the tenth to the nineteenth, etc– hkotsubo