How to append new data onto a new line

后端 未结 9 1758
一整个雨季
一整个雨季 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: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.

提交回复
热议问题