How to fix write file hard coded headers/footer when no records available to retrieve from database python and mysql

Question:

I am writing data to a file in Python from MYSQL databases tables with hardcoded headers and footer using the folowing code:

for record in cur.fetchall():
    filteredrecord = (record[0] + "t" + record[1])

    print(filteredrecord)


    feed_file = open("c:\test\test.txt", "w")
    feed_file.write("Name" + "t" + "Age" )
    feed_file.write("n" + (filteredrecord))
    feed_file.write("n" + "ENDOFFILE")
    feed_file.close()

This works fine when there are records present within the database table however when there are no records present in a database table i select from nothing gets written to my file not even my hardcoded headers and footer.

I get the following output when a record is present:

output when records on db table present

I would like to get the following written to my file when there are no records present:

output needed when no records present on db table

How can I get the above to write to file when there are no records within my database table?

Asked By: rob

||

Answers:

You have your entire code for opening the file, writing the header/footer and closing the file again, all within the for loop of iterating over the records returned from the query. In fact, if you have more than one record, it should keep opening the file, overwriting the content with the new record, including header/footer, and close the file.

What you want is to open the file once, write the header, then loop over the records and write each, then finally write the footer and close the file. The code might look something like this:

with open("c:\test\test.txt", "w") as feed_file:
    feed_file.write("Name" + "t" + "Age" )

    for record in cur.fetchall():
        filteredrecord = (record[0] + "t" + record[1])
        print(filteredrecord)
        feed_file.write("n" + (filteredrecord))

    feed_file.write("n" + "ENDOFFILE")

Note that you don’t need to close the file explicitly when using the with structure.

Answered By: Etienne Ott
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.