简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM