shell dude
shell dude

Reputation: 99

Rewriting file each time script is executing but appending at the same time in python

So i have a main python script which essentially calls another python script with arguments provided. My question is , each time it loops through files and writes to the file , but it appends when doing so.

If i was to run the script again , providing the same test-data folder , it would append to the file again. I want to be able to at each time i run the script , rewrite the whole file so it is empty and then append each file name to the file. Is this possible ?

My code is as follows for my main script :

def get_config():
    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--export-date", action="store", required=True)
    args = parser.parse_args()
    return [args.export_date]

Upvotes: 0

Views: 172

Answers (1)

Thodor
Thodor

Reputation: 43

Update: OK, I now understand you want to create a new file every time you run your main script. In this case I would just update the generate_json function:

def generate_json(path = get_json_location()):
    open('/path/to/your/file', 'w').close()
    for yml in yml_directory :
        print("Running export for " + yml)
        os.system('python generate_json.py -p' + path + ' -e  yaml/'  + yml + ' -d ' + date)

Forget what I said about the following line in your generate_json.py and leave it there with the 'a' argument:

with open('dates/' + current_day + '.json', 'a') as file:

Upvotes: 1

Related Questions