zoukankan      html  css  js  c++  java
  • python基础(四)

    file = open('女神集合',mode="r",encoding="utf-8")
    content = file.read()
    file.close()
    print(content)
    # 只读操作
    file = open('女神集合',mode="rb")
    content = file.read()
    file.close()
    print(content.decode('utf-8'))
    # 上面同样是只读操作但是读取的是字节码类型
    file = open('女神集合',mode="r",encoding="utf-8")
    content = file.read(1)
    content2 = file.read()
    file.close()
    print(content)
    print(content2)
    # read(n)读取n个字符.需要注意的是.如果再次读取.那么会在当前位置继续去读⽽不
    # 是从头读,如果使⽤的是rb模式.则读取出来的是n个字节
    file = open('女神集合',mode="r",encoding="utf-8")
    content = file.readline()
    file.close()
    print(content.strip())
    # readline()⼀次读取⼀⾏数据,注意: readline()结尾,注意每次读取出来的数据都会有⼀
    # 个
    所以呢.需要我们使⽤strip()⽅法来去掉
    或者空格
    file = open('女神集合',mode="w",encoding="utf-8")
    file.write("AAAA")
    file.flush()
    file.close()
    # 写的时候注意.如果没有⽂件.则会创建⽂件,如果⽂件存在.则将原件中原来的内容删除,再写入新内容
    file = open('女神集合',mode="wb")
    file.write("AAAA".encode('utf-8'))
    file.flush()
    file.close()
    # wb模式下.可以不指定⽂件的编码.但是在写⽂件的时候必须将字符串转化成utf-8的
    # bytes数据
    file = open('女神集合',mode='r+',encoding='utf-8')
    content = file.read()
    file.write('aaa')
    file.flush()
    file.close()
    print(content)
    
    # 读写模式: r+模式下.必须是先读取.然后再写入
    file = open('女神集合',mode='w+',encoding='utf-8')
    file.write('aaa')
    file.seek(0)
    content = file.read()
    file.flush()
    file.close()
    print(content)
    
    # 1.seek(n)光标移动到n位置,注意,移动的单位是byte.所以如果是UTF-8的中⽂部分要是3的倍数.
    # 通常我们使⽤seek都是移动到开头或者结尾.
    # 移动到开头: seek(0)
    # 移动到结尾: seek(0,2)  seek的第⼆个参数表⽰的是从哪个位置进⾏偏移,默认是0,表
    # ⽰开头, 1表⽰当前位置, 2表⽰结尾
    # tell()使⽤tell()可以帮我们获取到当前光标在什么位置
    
    # 深坑请注意:在r+模式下.如果读取了内容.不论读取内容多少.光标显⽰的是多少.再写入或者操作⽂件的时候都是在结尾进⾏的操作.
    # 修改⽂件以及另⼀种打开⽂件的⽅式
    # ⽂件修改:只能将⽂件中的内容读取到内存中,将信息修改完毕,然后将源⽂件删除,将新⽂件的名字改成老⽂件的名字.
    import os
    
    with open('吃的',mode='r',encoding='utf-8') as file1,
        open("吃的_副本",mode='w',encoding='utf-8') as file2:
        for line in file1:
            file2.write(line.replace('',''))
    os.remove('吃的')
    os.rename('吃的_副本','吃的')
  • 相关阅读:
    C# 访问AD查询用户信息
    js UTC时间转本地时间
    Silverlight中的序列化和反序列化
    ASP.NET FORM认证配置排错记录
    opencv中cvSetData用法
    WS2812B-64位 8*8位 RGB LED点阵
    1602 LCDKeypad Shield
    Wemos D1 使用ESP8266 板载存储
    Wemos D1 ESP8266的网络工作模式
    Wemos D1 1602 液晶屏幕
  • 原文地址:https://www.cnblogs.com/tengx/p/11699364.html
Copyright © 2011-2022 走看看