• 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" + " "+"
    ")
        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" + " "+"
    ")
        a +=1
    复制代码

      输出结果:

      

    总结:根据开始的表格,根据需要,更改open文件时的方式即可。

    说明:

    f.close需要加(),否则会关闭失败,后面无法再对文件进行读写操作

            f=open(filename+'.v',"w")
            f.write('module '+filename+'(
    ')
            f.write(msg)
            f.write('
    endmodule')
            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()
  • 相关阅读:
    蓝桥杯入门训练
    <泛> STL
    传递 hdu 5961 拓扑排序有无环~
    Alice and Bob hdu 4268
    Bipartite Graph hdu 5313 bitset 并查集 二分图
    Bomb HDU 3555 dp状态转移
    不要62 hdu 2089 dfs记忆化搜索
    Leaving Auction CF 749D
    Moo University
    算法(三)
  • 原文地址:https://www.cnblogs.com/zhiminyu/p/14153656.html
Copyright © 2020-2023  润新知