網頁

2025年7月30日 星期三

Python 文字檔的刪除資料

 一、主題介紹:

在文字檔 (.txt) 裡如前幾篇文章所講的查詢、新增、修改..外,還有刪除資料的功能,這就是今天要來探討的內容,刪除檔案資料的功能其實和修改資料的程式架構大同小異,都是要先讀取文字檔 (.txt) 內容資料後,再根據資料做修改或刪除的功能,等到處理完後再將變動的資料存回原本的文字檔 (.txt),即完成整個流程動作。


二、程式範例:

(1) 文字檔內容 (data.txt)

序 編號 公司 聯絡人 行動電話 備註

1 B001 加佳 張三 0900-123456

2 E150 億元 胡二 0900-111111

3 C455 成功 王八 0921-168168

4 E150 億元 胡二 0900-444444

5 D050 旺旺 鄭一 0900-888888

6 E150 億萬 胡二 0900-111111

7 E111 資源 方五 0900-333333

8 E222 億元 詹六 0900-222222


(2) 程式內容


class TxtAccess:

    def __init__(self,file):   #初始化
        self.__file = file

    def search(self):   #查詢
        with open(self.__file,"r",encoding="utf-8") as fobj:
            datas = fobj.read()
        return datas
   
    def newadd(self,datas):   #新增
        with open(self.__file,"a",encoding="utf-8") as fobj:
            fobj.write("\n")
            for i in range(0,len(datas),1):
                fobj.write(str(datas[i]))
                fobj.write(",")

    def modify(self,id,newdata):   #修改
        array = []
        with open(self.__file,"r",encoding="utf-8") as fobj:
            for line in fobj:
                row = line.strip().split()
                array.append([x for x in row])
        array[id] = newdata
        with open(self.__file,"w",encoding="utf-8") as fobj:
            for row in array:
                line = ' '.join(map(str,row))
                fobj.write(line+"\n")

    def delData(self,id):   #刪除
        array = []
        with open(self.__file,"r",encoding="utf-8") as fobj:
            for line in fobj:
                row = line.strip().split()
                array.append([x for x in row])
        array.pop(id)
        with open(self.__file,"w",encoding="utf-8") as fobj:
            for row in array:
                line = ' '.join(map(str,row))
                fobj.write(line+"\n")

   
    def show(self,data):   #顯示
        print(data)




file = "data.txt"
A = TxtAccess(file)
#刪除
A.delData(3)
sr = A.search()
A.show(sr)


# 執行結果

序 編號 公司 聯絡人 行動電話 備註

1 B001 加佳 張三 0900-123456

2 E150 億元 胡二 0900-111111

4 E150 億元 胡二 0900-444444

5 D050 旺旺 鄭一 0900-888888

6 E150 億萬 胡二 0900-111111

7 E111 資源 方五 0900-333333

8 E222 億元 詹六 0900-222222



三、程式說明:

由程式執行結果可以知道第3列的資料被刪除了,而刪除功能的程式就在類別方法的最後一個 delData() 函式,此程式內容就做到先讀取再刪除,刪除後將資料存回文字檔 (.txt) 內,使用了 pop() 內建函式,將要刪除的資料整列刪除。



沒有留言:

張貼留言

TQC+ Python 證照考題評量(五十四) - 平均溫度

 一、主題介紹: 資料庫中的一堆數據資料,時常需要這些資料的平均值、最大值、與最小值,作為分析資料的依據,如能透過寫程式讓它們自動化就能增加效率,就來看看今天的 TQC+ 考題的練習。 (1) 題目 請撰寫一程式,讓使用者輸入四週各三天的溫度,接著計算並輸出這四週的平均溫度及最高...