How to append new data onto a new line

后端 未结 9 1774
一整个雨季
一整个雨季 2020-12-02 16:41

My code looks like this:

def storescores():

   hs = open(\"hst.txt\",\"a\")
   hs.write(name)
   hs.close() 

so if I run it and enter \"Ry

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 17:17

    There is also one fact that you have to consider. You should first check if your file is empty before adding anything to it. Because if your file is empty then I don't think you would like to add a blank new line in the beginning of the file. This code

    1. first checks if the file is empty
    2. If the file is empty then it will simply add your input text to the file else it will add a new line and then it will add your text to the file. You should use a try catch for os.path.getsize() to catch any exceptions.

    Code:

    import os
    
    def storescores():
    hs = open("hst.txt","a")
    if(os.path.getsize("hst.txt") > 0):
       hs.write("\n"+name)
    else:
       hs.write(name)
    
    hs.close()
    

提交回复
热议问题