python txt文件讀寫(追加、覆蓋)


轉載:https://www.cnblogs.com/syw20170419/p/10972471.html

 

 

(1)在lucky.txt中新增內容(覆蓋:每次運行都會重新寫入內容)

復制代碼
f = "lucky.txt"

a =8
with open(f,"w") as file:   #”w"代表着每次運行都覆蓋內容
    for i in range(a):
        file.write(str(i) + "d" + " "+"\n")
    a +=1
復制代碼

輸出結果:

    

 

(2) 在lucky.txt中追加內容(追加:之前在txt中的內容不改變,繼續在已存在的內容后新增內容)

復制代碼
f = "lucky.txt"

a =8
with open(f,"a") as file:   #只需要將之前的”w"改為“a"即可,代表追加內容
    for i in range(a):
        file.write(str(i) + "d" + " "+"\n")
    a +=1
復制代碼

  輸出結果:

  

 

總結:根據開始的表格,根據需要,更改open文件時的方式即可。

說明:

f.close需要加(),否則會關閉失敗,后面無法再對文件進行讀寫操作

        f=open(filename+'.v',"w")
        f.write('module '+filename+'(\n')
        f.write(msg)
        f.write('\nendmodule')
        f.close() #若使用f.close,沒有(),則后面的open函數無法打開該文件
        #edit_file(filename)
        print("----------")
        with open("work_ctrl.v", "r+") as fp:
            print("fp is", fp)
            data = fp.readline()
            print(data)
        fp1 = open("D:/py_prj/rtl_split/venv/Include/b.v" , "r+")
        print(fp1)
        print(fp1.readable()) #可讀返回Ture
        print(fp1.readline())
        fp1.close()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM