zoukankan      html  css  js  c++  java
  • 文件读写

    f = open('文件路径', '模式')
    f=open('hello',“r”) data=f.read() print(data) f.close()
    "r"代表只读

    # read 只能读
    # f=open('hello','r')
    # 打开文件 创建对象
    # data=f.read()
    # 对度读取的数据进行赋值
    # f.close()
    # 最后打印
    # print(data)

    f=open('hello',"w")
    f.write("123")
    f.close()
    "w" 代表只写
    如果不存在hello这个文件,会创建新的文件hello,并写入信息
    如果hello存在,则会删除hello内的数据,重新写入现有信息

    f=open('hello',"x”)
    f.write("123")
    f.close()
    # "x" 也是只写
    # f=open("hello","x")
    # f.write()
    # f.close()
    # 跟上面的差不多,
    # 没有该文件的时候创建文件
    # 但是如果文件已经存在,会报错
     
    f=open("hello",“a”)
    f.write("6666")
    f.close()
    "a"代表追加哦
    在已有的hello中会接着前面的继续写入
    没有的话就继续创建并写入
    
    
    
    with的打开方式
    with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
        data=read_f.read()
        write_f.write(data)
    

     不用考虑关闭,这是最值得推荐的

     
    文件的修改
    方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘

    import os
    with open("hello","r") as  hello_read,with open("hello1",'w') as hello_write:
        data=hello_read.read()
        data1=data.replace("alex","SB")
        hello_write.write(data1)
    os.remove("hello")
    os.rename("hello1","hello")
    
    

     方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件

    with open("hello","r",encoding="utf-8") as f,open("hello1","w") as f1:
        # data=f.read()
        for line in f:
    
            line1=line.replace("SB","alex")
            f1.write(line1)
    os.remove("hello")
    os.rename("hello1","hello")
    
    
  • 相关阅读:
    Codeforces 220C
    Codeforces 697D
    HDU 4417
    Codeforces 396C
    Codeforces 246C
    HDU 6333
    HDU 3389
    总结:树上启发式合并
    HDU 6319
    Codeforces 1009G
  • 原文地址:https://www.cnblogs.com/zhange000/p/9110838.html
Copyright © 2011-2022 走看看