Python continuous writing failed

This question already has an answer here:

  • How do you append to a file? 8 answers

  • This is too much of code for the File Open and Write, You can just use this following lines to append the text in your file

    def FileSave(filename,content):
        with open(filename, "a") as myfile:
            myfile.write(content)
    
    FileSave("test.txt","test1 n")
    FileSave("test.txt","test2 n")
    

    Here, when we using this line open(filename, "a") , the a indicates the appending the file, that means allow to insert extra data to the existing file


    as stated in the python doc you need to open your file with mode='a' if you want to append to existing data; mode='w' simply overwrites:

    with open(file='_test.txt', mode='a') as file:
        file.write('test')
    

    (if you are using python 2, change the variable name file above to something else; in python 2 file is a keyword).


    The reason for your "Worry Output" is that you re-open "test.txt" in read mode inside openfile after you've already opened it in write mode outside the functions. When you open a file in write mode it gets truncated, ie, the file pointer is positioned to the start of the file and the current contents of the file are discarded. So when you call openfile inside write_file the file is empty, and thus openfile returns an empty list.

    Here's a repaired version of your code. We use try... except in openfile so we can return an empty list if the file doesn't exist.

    def openfile(fname):
        try:
            f = open(fname, "r")
            contents = f.readlines()
            f.close()
            return contents
        except FileNotFoundError:
            return []
    
    def write_file(contents, fname):
        old_contents = openfile(fname)
        old_contents.insert(1,contents)
        contents = "".join(old_contents)
        f = open(fname, "w")
        f.write(contents)
        f.close()
    
    contents= "test1 n"
    write_file(contents, "test.txt")
    
    contents = "test2 n"
    write_file(contents, "test.txt")
    

    And here are the contents of "test.txt" after running that code:

    test1 
    test2 
    

    Actually, it's better to use with when opening files:

    def openfile(fname):
        try:
            with open(fname, "r") as f:
                contents = f.readlines()
            return contents
        except FileNotFoundError:
            return []
    
    def write_file(contents, fname):
        old_contents = openfile(fname)
        old_contents.insert(1,contents)
        contents = "".join(old_contents)
        with open(fname, "w") as f:
            f.write(contents)
    

    However, a much better way to do this is to simply open the file in append mode as hiro protagonist and K.Suthagar have already shown. But I figured it was a good idea to explain why your current code didn't do what you expected it to do.

    链接地址: http://www.djcxy.com/p/42414.html

    上一篇: Python tempfile [Errno 66]目录不为空

    下一篇: Python连续写入失败