[SOLVED] How do I empty out a file’s text into another file?


This Content is from Stack Overflow. Question asked by ProgramProdigy

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()
    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')

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

    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:

This Question was asked in StackOverflow by ProgramProdigy and Answered by bitflip It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?