How to fix write file hard coded headers/footer when no records available to retrieve from database python and mysqlHow do I connect to a MySQL Database in Python?Restoring MySQL database from physical filesHow do I create a CSV file from database in Python?How can I find script's directory with Python?How to read a text file into a string variable and strip newlines?ERROR 2006 (HY000): MySQL server has gone awayHow to overcome “datetime.datetime not JSON serializable”?SQL query return data from multiple tablesReference - What does this error mean in PHP?“Large data” work flows using pandas

How to realistically deal with a shield user?

Identify Batman without getting caught

Is there a way to improve my grade after graduation?

How do I get the =LEFT function in excel, to also take the number zero as the first number?

Can you take actions after being healed at 0hp?

Why do cheap flights with a layover get more expensive when you split them up into separate flights?

Purchased new computer from DELL with pre-installed Ubuntu. Won't boot. Should assume its an error from DELL?

Ancients don't give a full level?

Find only those folders that contain a File with the same name as the Folder

How important is it to have a spot meter on the light meter?

I was contacted by a private bank overseas to get my inheritance

Ubuntu show wrong disk sizes, how to solve it?

Can a Hogwarts student refuse the Sorting Hat's decision?

Make a living as a math programming freelancer?

Repeated! Factorials!

Does the length of a password for Wi-Fi affect speed?

How can I perform a deterministic physics simulation?

Homogenous Equation ODE

Is an "are" omitted in this sentence

Generate a random point outside a given rectangle within a map

Traveling from Germany to other countries by train?

How to check a file was encrypted (really & correctly)

Which pronoun to replace an infinitive?

If someone else uploads my GPL'd code to Github without my permission, is that a copyright violation?



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


How do I connect to a MySQL Database in Python?Restoring MySQL database from physical filesHow do I create a CSV file from database in Python?How can I find script's directory with Python?How to read a text file into a string variable and strip newlines?ERROR 2006 (HY000): MySQL server has gone awayHow to overcome “datetime.datetime not JSON serializable”?SQL query return data from multiple tablesReference - What does this error mean in PHP?“Large data” work flows using pandas






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















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. Thanks










share|improve this question






























    0















    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. Thanks










    share|improve this question


























      0












      0








      0








      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. Thanks










      share|improve this 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. Thanks







      python mysql






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 27 at 4:03









      robrob

      73 bronze badges




      73 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          0














          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.






          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55369619%2fhow-to-fix-write-file-hard-coded-headers-footer-when-no-records-available-to-ret%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            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.






            share|improve this answer





























              0














              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.






              share|improve this answer



























                0












                0








                0







                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.






                share|improve this answer













                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.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 27 at 8:07









                Etienne OttEtienne Ott

                3781 silver badge8 bronze badges




                3781 silver badge8 bronze badges





















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55369619%2fhow-to-fix-write-file-hard-coded-headers-footer-when-no-records-available-to-ret%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현