I am following the code mentioned by SO User "qmorgan" here, basically I am trying to create new text file if file doesn't exist. If file exist then overwrite the existing file. For this my code looks like below. The issue I am facing is using 'a' for writing the file it is append the text instead of overwriting it. As 'a' function is to append the text under first if condition. If I use "W" instead of "a" then it would only write last record, instead of all the records.
Thanks in advance for help and efforts!
Python code
filename='test.txt'
tables=["schema.table1","schema2.table2"]
for table in tables:
cur.execute (f'select count(*) from {table};')
result=cur.fecthone()
count=result[0] if result else 0
for row in result:
if os.path.exists(filename):
append_write='a'
my_file.close()
else:
append_write='w+'
my_file=open(filename,append_write)
my_file.write(f"the table {table} contained {count} rows. \n")
my_file.close()