简体   繁体   English

如何将文件的文本清空到另一个文件中?

[英]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.目前,我为此使用 fs.truncate 方法,但它不起作用。 Please suggest any useful methods for this.请为此建议任何有用的方法。 I am using python.我正在使用 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).我认为您需要使用 r+ 打开文件并使用 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果文本文件的内容不同,如何将它们替换为另一个? - How do I replace a text file's contents with another if they are different? Python,如何从另一个文本文件中的文本中删除文本? - Python, How do I Remove Text From a Text From That's in Another Text File? 如何从一个文本文件中提取单词? 蟒蛇 - How do I take words from one text file out of another? Python 如何从每一行文本中读取特定字符并将其写到另一个文件中? - How do I read in specific characters from each line of text and write it out to another file? 如何在另一个文本文件python中保存文本 - how do I save a text in another text file python 在Python中,如何将基于扩展名的文件名从文本文件中拉出并放入新的文本文件中? - In Python, how do I pull the file name based on extension out of a text file and place in new text file? 如何从文本文件中删除特定行? - How do I remove a specific line out of a text file? 如何在python中检查另一个用户的文件权限? - How do I check another user's file permissions in python? 如何将生成器的 output 写入文本文件? - How do I write a generator's output to a text file? Python文件I / O:实现将一个文本文件的内容复制到一个空文本文件的功能 - Python File I/O: Implementing a function that copy's the content of one text file to an empty text file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM