打開一個文本;關閉時如果發現有改動,會提示覆蓋還是另存爲
import easygui as eg
import os
#文件路徑
file_path = eg.fileopenbox(default="*.txt")
#打開文件
with open(file_path)as f:
#把文件讀取的內容放到text中
text = f.read()
# title 使用文件名
title = os.path.basename(file_path)
#窗口消息
msg = "文件 [%s] 的內容如下:" % title
#建立一個文本框, 讀取文本內容 給他定義一個變量,是一會兒下面要調用他
text_after = eg.textbox(msg, title, text)
#判斷是否有修改,就是判斷text 讀取的內容是不是等於文本框text_after裏的內容就行了
#因爲textbox最後一行會返回\n. 所以往前取一個字符.[:-1]
if text != text_after[:-1]:
#如果文件被修改的時候,會彈出一個框,
choice = eg.buttonbox(msg="文件有修改", title="警告!", choices=("覆蓋", "取消", "另存爲"))
if choice == "覆蓋":
#把text_after[:-1]的內容寫到原文件裏面,
with open(file_path, "w") as old_file:
old_file.write(text_after[:-1])
if choice == "取消":
pass
if choice == "另存爲":
#如果點另存爲,那就彈出一個file save box窗口,保存文件,
anther_path = eg.filesavebox(default=".txt")
#如果保存文件的時候沒有後綴.txt 那就 自動添加一個後綴
if os.path.splitext(anther_path)[1] != ".txt":
anther_path += ".txt"
#把文件寫到新保存的文件中
with open(anther_path, "w")as new_file:
new_file.write(text_after[:-1])