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()

 

posted @ 2020-12-18 10:28  burlingame  阅读(7352)  评论(0编辑  收藏  举报