马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
答案中给的代码抄了一遍,为啥运行结果不对啊?每次不管选择“覆盖保存”,“放弃保存”或者“不保存”,我原来文档中的最后一个字总是会被删掉。这是为什么?import easygui as eg
import 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)[1]!='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)[1] != '.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
|