zoukankan      html  css  js  c++  java
  • 扩展模式 + w+ r+ a+

    # ### 扩展模式 +  w+ r+ a+ 
    '''
    # (utf-8编码格式下 默认一个中文三个字节 一个英文或符号 占用一个字节)
        #read()		功能: 读取字符的个数(里面的参数代表字符个数)
        #seek()		功能: 调整指针的位置(里面的参数代表字节个数)
        #tell()		功能: 当前光标左侧所有的字节数(返回字节数)
    	
    把光标移动到文件行首
    fp.seek(0)
    把光标移动到文件末尾
    fp.seek(0,2)
    '''
    # r+ 可读可写 (先读后写)
    '''
    fp = open("0506_3.txt",mode="r+",encoding="utf-8")
    res = fp.read()
    # print(res)
    fp.write("e")
    # 把光标移动到第0个字节上,那就是文件开头
    fp.seek(0)
    res = fp.read()
    print(res)
    fp.close()
    '''
    # r+ 可读可写 (先写后读)
    '''
    fp = open("0506_3.txt",mode="r+",encoding="utf-8")
    # 把光标移动到文件末尾
    fp.seek(0,2)
    fp.write("123")
    fp.seek(0)
    res = fp.read()
    print(res)
    fp.close()
    '''
    # w+ 可读可写 
    '''
    fp = open("0506_4.txt",mode="w+",encoding="utf-8")
    fp.write("11122233")
    fp.seek(0)
    res = fp.read()
    print(res)
    fp.close()
    '''
    
    # a+ 可读可写 append (写入的时候,强制把光标移动到最后)
    '''
    fp = open("0506_4.txt",mode="a+",encoding="utf-8")
    fp.seek(0)
    fp.write("444")
    fp.seek(0)
    res = fp.read()
    print(res)
    fp.close()
    '''
    
    # tell read seek  注意 seek括号里的是字节数 read括号里的是字符数
    '''
    fp = open("0506_4.txt",mode="a+",encoding="utf-8")
    res = fp.tell()
    print(res) 
    fp.seek(5)
    res = fp.tell()
    print(res)
    res = fp.read(2) # 读取2个字符
    res = fp.tell()
    print(res)
    fp.close()
    '''
    
    # 注意有中文的情况 , 如果移动错误,有可能读取不出来.
    '''
    fp = open("0506_4.txt",mode="a+",encoding="utf-8")
    res = fp.tell()
    print(res)
    fp.seek(2)
    res = fp.tell()
    print(res)
    fp.read(2)
    res = fp.tell()
    print(res)
    fp.seek(5)
    res = fp.tell()
    print(res)
    res = fp.read()
    fp.close()
    
    # xa1xa2xa3
    '''
    
    # with 操作
    # with 语法 自动关闭文件 相当于帮你执行了fp.close()
    # as 相当于起别名 fp = open("0506_5.txt",mode="w",encoding="utf-8") with 是一个代码块 不要落下冒号:
    with open("0506_5.txt",mode="w",encoding="utf-8") as fp:
    	# 往文件里面写的内容只能是字符串 或者 字节流
    	fp.write("123")
    	
    

      

  • 相关阅读:
    细节问题
    慕课 python 操作数据库
    转 Python爬虫入门七之正则表达式
    转 python面试题
    转 Perl函数返回值用法指导
    慕课爬虫实战 爬取百度百科Python词条相关1000个页面数据
    慕课爬虫
    转 Python爬虫入门五之URLError异常处理
    转 廖雪峰 urllib
    转 Python爬虫入门四之Urllib库的高级用法
  • 原文地址:https://www.cnblogs.com/huangjiangyong/p/10823137.html
Copyright © 2011-2022 走看看