轉載: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()