简体   繁体   中英

How do I empty out a file's text into another file?

I am trying to make my code so that it simulates a chat. So far, I have no problem doing that, but the problem is, I want to make it so that when the chat reaches a certain amount of lines, it purges the chat and empties out the content of the text file into another archive file. Currently, I am using fs.truncate method for this, but it is not working. Please suggest any useful methods for this. I am using python.

fs = open("forum.text", 'r')
    root3 = Tk()
    root3.geometry('500x500')
    full_chat = Label(root3, text=fs.read(), font=('Arial', 8, "bold")).pack()
    chat_text = Text(root3, height=5)
    line_count = len(fs.readlines())
    if line_count in [32, 33, 34, 35, 36, 37]:
        fs4 = open("forum.text", 'a')
        fs4.write("\nChat is purging soon! Beware!")
    elif line_count >= 38:
        fs2 = open("forum.text", 'w')
        fs3 = open("archive.text", 'w')
        fs3.write(fs.read())
        fs2.truncate()
    
    chat_text.pack()

    def post_msg():
        msg = chat_text.get('1.0', 'end-1c')
        fs1 = open("forum.text", 'a')
        fs1.write('\n' + username + ' says: ' + msg)
        fs1.close()
        root3.destroy()
        forum(username)

    Button(root3, text="Post to Chat", command=post_msg).pack()

I think you need to open your file with r+ and use truncate(0). Like that

with open('file1.txt', 'r+') as firstfile, \
    open('file2.txt', 'a') as secondfile:
    for line in firstfile:
        secondfile.write("\nline")
    firstfile.truncate(0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM