[英]How do I replace a text file's contents with another if they are different?
[英]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.