pythonpython-zipfile

Convert and move .zip and .xml


I'm trying to make a program where I convert and move the files, but I'm not succeeding, the error always indicates the paths that I put, but I don't know how to solve it.

from zipfile import ZipFile
import os
import xmltodict, json

## Extract the ZIP files
zipCemig = ZipFile('Consulta_Saldo_GD.zip', 'r')
zipCemig.extract('C:/Users/andre.friedrich/Desktop/Bot CEMIG/XML Cemig')

## Convert XML files
xml = 'C:/Users/andre.friedrich/Desktop/Bot CEMIG/XML Cemig'
lista = os.listdir(xml)
lista_len = len(lista)
x = 0
while x < lista_len:
    with open(lista) as f:
        d = xmltodict.parse(f.read())
    with open("cemig"+x+".json", 'w') as f:
        json.dump(d, f)
    x += 1

## Move already converted files
oldAdress = 'C:/Users/andre.friedrich/Desktop/Bot CEMIG/XML Cemig'
newAdressXml = 'C:/Users/andre.friedrich/Desktop/Bot CEMIG/XML Arquivo Morto'
newAdressJson = 'C:/Users/andre.friedrich/Desktop/Bot CEMIG/JSON Cemig'
lista = os.listdir(oldAdress)
for arquivo in lista:
    if ".xml" in arquivo:
        os.rename(f"{oldAdress}/{arquivo}", f"{newAdressXml}/{arquivo}")
    if ".json" in arquivo:
        os.rename(f"{oldAdress}/{arquivo}", f"{newAdressJson}/{arquivo}")

I would like the program to convert and move the files to the indicated paths.

I'm also getting an error

TypeError: ZipFile.extract() missing 1 required positional argument: 'member'

Solution

  • Seems like it could be the backslashes in the file paths. In Python, backslashes are used to escape special characters, so they need to be escaped themselves by using another backslash.

    Also in the last loop where you convert the XML to the .json I would rephrase it more to look like this

    for arquivo in lista:
        if arquivo.endswith(".xml"):
            os.rename(os.path.join(oldAdress, arquivo), os.path.join(newAdressXml, arquivo))
        if arquivo.endswith(".json"):
            os.rename(os.path.join(oldAdress, arquivo), os.path.join(newAdressJson, arquivo))