easygui的课后第三题
答案中给的代码抄了一遍,为啥运行结果不对啊?每次不管选择“覆盖保存”,“放弃保存”或者“不保存”,我原来文档中的最后一个字总是会被删掉。这是为什么?import easygui as egimport os
f=open('C:\\Users\\hp\\Desktop\\juli.txt',errors='ignore',encoding='utf-8')
title='juli'
msg='文件【juli】的内容如下:'
text=f.read()
f.seek(0,0)
text_after=eg.textbox(msg,title,text=f.read())
f.close()
if text!=text_after[:-1]:
jieguo=eg.buttonbox('检测到文件内容发生改变,请选择以下操作:',\
title='警告',choices=['覆盖保存','放弃保存','另存为...'])
if jieguo=='覆盖保存':
a=open('C:\\Users\\hp\\Desktop\\juli.txt','w',errors='ignore',encoding='utf-8')
a.write(text_after[:-1])
a.seek(0,0)
a.close()
if jieguo=='放弃保存':
pass
if jieguo=='另存为...':
another_path=eg.filesavebox(default='C:\\Users\\hp\\Desktop\\.txt')
if os.path.splitext(another_path)!='C:\\Users\\hp\\Desktop\\.txt':
another_path+='.txt'
with open(another_path,'w') as newfile:
newfile.write(text_after[:-1])
import easygui as g
import os
file_path = g.fileopenbox(default="*.txt")
with open(file_path, encoding='utf-8') as old_file:
title = os.path.basename(file_path)
msg = "文件【%s】的内容如下:" % title
text = old_file.read()
text_after = g.textbox(msg, title, text)
if text != text_after: #text_after[:-1]
#小甲鱼的答案说textbox 的返回值会追加一个换行符,我运行的结果不会,故将text_after[:-1]改为了text_after
choice = g.buttonbox("检测到文件内容发生改变,请选择以下操作:", "警告", ("覆盖保存", "放弃保存", "另存为..."))
if choice == "覆盖保存":
with open(file_path, "w", encoding='utf-8') as old_file:
old_file.write(text_after)#text_after[:-1]
if choice == "放弃保存":
pass
if choice == "另存为...":
another_path = g.filesavebox(default=".txt")
if os.path.splitext(another_path) != '.txt':
another_path += '.txt'
with open(another_path, "w", encoding='utf-8') as new_file:
new_file.write(text_after)#text_after[:-1]
应该是版本的问题,详见https://blog.csdn.net/qq_41556318/article/details/84318433 题目是:打开文本文件,并显示文件内容;当用户点击‘OK’按钮时,比较当前文件是否修改过,如果修改过,则提示‘覆盖保存’,‘放弃保存或‘另存为...’’ 老八秘制 发表于 2020-4-18 10:05
应该是版本的问题,详见https://blog.csdn.net/qq_41556318/article/details/84318433
对了!谢谢你 绵绵haha 发表于 2020-4-18 10:17
对了!谢谢你
设个最佳谢谢~ 绵绵haha 发表于 2020-4-18 10:17
对了!谢谢你
不好意思啊,我这个没设成‘问题求助’,所以选不了最佳答案。给你的回答置顶啦 绵绵haha 发表于 2020-4-18 10:38
不好意思啊,我这个没设成‘问题求助’,所以选不了最佳答案。给你的回答置顶啦
帮你改成问题求助了,设他为最佳吧
P.S:可以自己编辑帖子改帖子类型的
页:
[1]