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.