簡體   English   中英

如何將文件的文本清空到另一個文件中?

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

我正在嘗試制作我的代碼,以便模擬聊天。 到目前為止,我這樣做沒有問題,但問題是,我想讓它在聊天達到一定數量的行時,它會清除聊天並將文本文件的內容清空到另一個存檔文件中。 目前,我為此使用 fs.truncate 方法,但它不起作用。 請為此建議任何有用的方法。 我正在使用 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()

我認為您需要使用 r+ 打開文件並使用 truncate(0)。 像那樣

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM