How to append new data onto a new line

后端 未结 9 1729
一整个雨季
一整个雨季 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()
    
    0 讨论(0)
  • 2020-12-02 17:19

    You need to change parameter "a" => "a+". Follow this code bellows:

    def storescores():
    hs = open("hst.txt","a+")
    
    0 讨论(0)
  • 2020-12-02 17:22

    The answer is not to add a newline after writing your string. That may solve a different problem. What you are asking is how to add a newline before you start appending your string. If you want to add a newline, but only if one does not already exist, you need to find out first, by reading the file.

    For example,

    with open('hst.txt') as fobj:
        text = fobj.read()
    
    name = 'Bob'
    
    with open('hst.txt', 'a') as fobj:
        if not text.endswith('\n'):
            fobj.write('\n')
        fobj.write(name)
    

    You might want to add the newline after name, or you may not, but in any case, it isn't the answer to your question.

    0 讨论(0)
提交回复
热议问题