Using Try: and Finally: to delete an existing file and write the new output to the file

StackOverflow https://stackoverflow.com/questions/14040781

  •  12-12-2021
  •  | 
  •  

Pregunta

I was trying to check and delete an existing output file, and write on a new file. However, my code didn't seem to work because it only captures the output from the last iteration.

# delete inactive contracts from dict()
for key, item in contracts.items():
    if item['contract_status'] == 'Inactive':
        del contracts[key]
    else:
        if os.path.exists(main_path):
            try:
                os.remove(main_path)
            finally:
                outfile = open(main_path, 'a')
                outfile.write(item['name'])
                outfile.write('\n')
            outfile.close()
¿Fue útil?

Solución

Instead of removing the file, just open it for writing:

else:
    with open(main_path, 'w') as outfile:
        outfile.write(item['name'])
        outfile.write('\n')

Opening a file with w truncates the file first, so data written to it replaces the old contents. Note that you are writing the file for each iteration in the loop.

By using the file as a context manager (with ..) it's closed automatically.

If you want to write all entries to the file, open the file outside of the loop:

with open(main_path, 'w') as outfile:
    for key, item in contracts.items():
        if item['contract_status'] == 'Inactive':
            del contracts[key]
        else:
            outfile.write(item['name'])
            outfile.write('\n')

If you need to re-write the file only if there are no inactive items in contracts, use:

contracts = {k: v for k, v in contracts.iteritems() if v['contract_status'] != 'Inactive'}
if contracts:
    with open(main_path, 'w') as outfile:
        for contract in contracts.values():
            outfile.write(item['name'])
            outfile.write('\n')

Now you first remove the inactive items, then if there are still contracts left, write those out to the file. If there are none left, the main_path file is left untouched.

Otros consejos

outfile = open(main_path, 'w') # this truncates existing file if any

# delete inactive contracts from dict()
for key, item in contracts.items():
    if item['contract_status'] == 'Inactive':
        del contracts[key]
    else:
        outfile.write(item['name'])
        outfile.write('\n')

outfile.close()

should it be rewritten into such a like one?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top