-2

I just got to know the world of programming and python was the first thing I learned.. This program already can extract data from .txt file and send it to API.. But the things is I don't know how to delete the file,after the data have been extracted and send to the API... Here is my coding...

from fileinput import close
import os
import requests
from datetime import datetime
import glob
import time

'''List'''
data_send_list = []

'''Path'''
path = "./file"

'''File List'''
file_name = []

URL = 'http://.......'

def main():
    
    #Main
    print("Main Def" "\n")

    #ScanFile
    data_send_list = scan_files(path)
    
    #send_API
    for json in data_send_list:
        send_api(URL, json)

def read_text_file(file_path):
    with open (file_path, 'r') as file:
        data_dictionary={}
        data = file.readlines()

        ...............

        '''UPDATE THE DICTIONARY'''
        data_dictionary.update([(...)(...)])

        return data_dictionary

def scan_files(path):
    list = []

    os.chdir(path)
    for file in glob.glob("*.txt"):
        list.append(read_text_file(file))
        
    return list

def send_api(url,json,):

    requests_session = requests.session()

    post_api = requests_session.post(url,data=json)
    print("Sending API")

    if(post_api.status_code >= 200 and post_api.status_code <300):
        print("Successful. Status code: ",post_api.status_code)
        print("\n")
#i hope that i can delete the file here

    else:
        print("Failed to send to API. Status code: ",post_api.status_code)
        print("\n")
        close()

    return post_api.status_code

I was hoping that if the data can be sent to API... and give output "status code: 200" the data file will be deleted... while the data that is not sent, the file will remain

  • Using `os.remove` you may remove the file. – Tony Montana Jun 16 '22 at 05:27
  • 1
    Does this answer your question? [How do I delete a file or folder in Python?](https://stackoverflow.com/questions/6996603/how-do-i-delete-a-file-or-folder-in-python) – Javad Jun 16 '22 at 06:28

1 Answers1

1

There would be a lot of better ways other than my answer.

import os

...

def send_api(url,json,path):  # You need to add function parameter path to use at this function

    requests_session = requests.session()

    post_api = requests_session.post(url,data=json)
    print("Sending API")

    if(post_api.status_code >= 200 and post_api.status_code <300):
        print("Successful. Status code: ",post_api.status_code)
        print("\n")
        os.remove(path)  # use os.remove function to remove file

    else:
        print("Failed to send to API. Status code: ",post_api.status_code)
        print("\n")
        close()

    return post_api.status_code
Lazyer
  • 917
  • 1
  • 6
  • 16