How to append new data onto a new line

后端 未结 9 1728
一整个雨季
一整个雨季 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 16:58

    All answers seem to work fine. If you need to do this many times, be aware that writing

    hs.write(name + "\n")
    

    constructs a new string in memory and appends that to the file.

    More efficient would be

    hs.write(name)
    hs.write("\n")
    

    which does not create a new string, just appends to the file.

    0 讨论(0)
  • 2020-12-02 17:00

    I presume that all you are wanting is simple string concatenation:

    def storescores():
    
       hs = open("hst.txt","a")
       hs.write(name + " ")
       hs.close() 
    

    Alternatively, change the " " to "\n" for a newline.

    0 讨论(0)
  • 2020-12-02 17:01

    I had the same issue. And I was able to solve it by using a formatter.

    file_name = "abc.txt"
    new_string = "I am a new string."
    opened_file = open(file_name, 'a')
    opened_file.write("%r\n" %new_string)
    opened_file.close()
    

    I hope this helps.

    0 讨论(0)
  • 2020-12-02 17:07

    In Python >= 3.6 you can use new string literal feature:

    with open('hst.txt', 'a') as fd:
        fd.write(f'\n{name}')
    

    Please notice using 'with statment' will automatically close the file when 'fd' runs out of scope

    0 讨论(0)
  • 2020-12-02 17:12

    If you want a newline, you have to write one explicitly. The usual way is like this:

    hs.write(name + "\n")
    

    This uses a backslash escape, \n, which Python converts to a newline character in string literals. It just concatenates your string, name, and that newline character into a bigger string, which gets written to the file.

    It's also possible to use a multi-line string literal instead, which looks like this:

    """
    """
    

    Or, you may want to use string formatting instead of concatenation:

    hs.write("{}\n".format(name))
    

    All of this is explained in the Input and Output chapter in the tutorial.

    0 讨论(0)
  • 2020-12-02 17:15
    import subprocess
    subprocess.check_output('echo "' + YOURTEXT + '" >> hello.txt',shell=True)
    
    0 讨论(0)
提交回复
热议问题