|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import easygui as g
import os
file = g.fileopenbox(default = '*.txt')
with open(file) as f:
title = os.path.basename(file)
msg = '文件【%s】内容如下:'% title
text = f.read()
text_after = g.textbox(msg,title,text)
if text != text_after:
choice = g.buttonbox('检测到文件内容改变,请选择操作:','警告',('覆盖保存','放弃保存','另存为'))
if choice == '覆盖保存':
with open (file,'w')as f:
f.write(text_after)
if choice =='放弃保存':
pass
if choice =='另存为':
another_path = g.filesavebox(default = '.txt')
if os.path.splitext(another_path)[1]!='.txt':
anotner_path +='.txt'
with open (another_path,'w')as newfile:
newfile.write(text_after)
原先的text != text_after[:-1] 已经改成 text != text_after 了,新的问题出现了,为什么文档打开后在无任何修改的情况下选择Cancel,还会弹出“检测到文件内容改变”呢???
因为如果选择 Cancel 选项,那么 textbox 就会返回 None ,导致 text != text_after
你需要在 if text != text_after 之前加个 if 判断 text_after 是否为 None,若为就退出程序反之继续程序
另外你最后 anotner_path 变量名错了 改成 another_path
参考代码:
import easygui as g
import os
file = g.fileopenbox(default = '*.txt')
with open(file) as f:
title = os.path.basename(file)
msg = '文件【%s】内容如下:'% title
text = f.read()
text_after = g.textbox(msg,title,text)
if text_after == None:
exit()
if text != text_after:
choice = g.buttonbox('检测到文件内容改变,请选择操作:','警告',('覆盖保存','放弃保存','另存为'))
print(choice)
if choice == '覆盖保存':
with open (file,'w')as f:
f.write(text_after)
if choice =='放弃保存':
pass
if choice =='另存为':
another_path = g.filesavebox(default = '.txt')
if os.path.splitext(another_path)[1]!='.txt':
another_path +='.txt'
with open (another_path,'w')as newfile:
newfile.write(text_after)
|
|