Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overwriting an existing txt file with new data using Python OS module

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

>Solution :

Just open the file once at the beginning, not separately for each query. Then you can simply use w mode to overwrite it.

There’s also no need for the for row in result: loop, since you never use row anywhere. result is a tuple with just a single element, the count returned by COUNT(*), there’s nothing else to loop over.

filename='test.txt'
  
tables=["schema.table1","schema2.table2"]
    
with open(filename, 'w') as my_file:
    for table in tables:
        cur.execute(f'select count(*) from {table};')
        (count,) = cur.fetchone()
        my_file.write(f"the table {table} contained {count} rows. \n")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading