zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    linux启动流程
    监控命令
    ansible组
    公钥和秘钥
    SSH协议介绍
    Java并发编程笔记之ThreadLocal内存泄漏探究
    【死磕 Java 集合】— ConcurrentSkipListMap源码分析
    GraphX介绍
    Storm内部的消息传递机制
    JanusGraph Server配置
  • 原文地址:https://www.cnblogs.com/zhiminyu/p/14153656.html
Copyright © 2011-2022 走看看