Ignore file with Python

1

I'm developing a client that le .JSON files and sends them to an API. The files are periodically deposited into a folder. However, what I want is that when an error occurs with the file (file being used, file with syntax error, etc.), that file is moved to another folder and client ignore this file and keep reading the others. How can I do it?

Follow me code so far:

    for file in glob.glob(diretorioIn +'*.json'):

        print("Iniciando Leitura")

        try:

            payload = json.load(open(file))

            print(file)

            print(payload)
            print(file)

            headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
            url = 'http://10.24.1.71/track/add'


            result = requests.post(url, data=json.dumps(payload), headers=headers)

            print(result.text)              
            os.remove(file)

        except ValueError:
            print("Arquivo com erro: ")
            print(file)
            os.rename(file, diretorioErro)

        except PermissionError:
            print("Arquivo está sendo usado. Será movido para a pasta ERROR")
            print(file)
            os.rename(file, diretorioErro)



print("Nenhum arquivo encontrado. Reprocessando WebService")
    
asked by anonymous 13.04.2017 / 17:24

1 answer

0

What you can do is to mark these files that are being used or with errors, because from the moment they are in use you will not be able to move them. Put their path into a list / dict object and remove them later or at a time that ensures they are freed.

Tip, read the file using the with statement:

with open(file_path) as df:
   data = json.load(df)

So you avoid leaving it open.

    
13.04.2017 / 20:18