• python--文件操作


    一,文件操作
    建立文件:老师.txt
    文件路径:b:老师.txt
    编码方式:utf-8 gbk
    操作方式:只读、只写、读写、写读····
    注:以什么编码方式储存的文件,就以什么编码打开进行操作。·
    文件打开后,都要在结尾加上f.close(),表示关闭文件,以免占用内存
    1.只读:r rb
    美丽.txt
    1:r
    相对路径:
    f=open(‘美丽.txt’,mode='r',encoding='utf-8')------>打开文件
    d=f.read()-----》把文件内容读出来赋值给d
    prind()------>打印文件内容
    绝对路径:首先在根目录下创建:d:美丽.txt
    f=open(‘d:美丽.txt’,mode='r',encoding='utf-8')------>打开文件
    注:报错两个原因,一个是创建文件 拓展名隐藏了,导致调取的文件不是一个文件;另一个原因是编码方式有误,文件用什么编辑的就要用什么方式打开
    2:rb
    f=open(‘美丽.txt’,mode='rb’)
    注:不用再写上编码方式了,rb,已经表明是bytes  类型了
    prind(f.read())
    只读

       2.读写:r+    r+b

    1.r+读写
    f=('美丽.txt',mode='r+',encoding='utf-8')
    print(f.read())
    f.close()
    2.r+b 读写(以bytes类型)
    f=('美丽.txt',mode='r+b')   #默认bytes 类型,不在写编码方式了
    print(f.read())
    f.close()
    读写

      3.只写:w  w+b  w+

    1.w
     先将源文件的内容全部清除,在写。
     f = open('log',mode='w',encoding='utf-8')
     f.write('附近看到')
     f.close()
    2.wb 已bytes类型写
     f = open('log',mode='w')
     f.write('附近看到'.encode('utf-8'))   #
     f.close()
    3.    w+   写读
      f = open('log',mode='w+',encoding='utf-8')
      f.write('aaa')
      f.seek(0)
      print(f.read())
      f.close()
    只写

      4.追加

        1.a  
            f = open('log',mode='a',encoding='utf-8')
            f.write('佳琪')
            f.close()
        2.ab
            f = open('log',mode='ab')
            f.write('佳琪'.encode('utf-8'))
            f.close()
    追加
    二、编码:什么方式编码的,就用什么方式解码
    #str --->byte  encode 编码
    b='中国'
    s1=b.encode('utf-8')
    编码
    byte --->str decode 解码
    b="中国“
    s1 = b.decode('utf-8')
    解码

    三、功能详解

    1.
    obj = open('log',mode='r+',encoding='utf-8')
    content = f.read(3) # 读出来的都是字符
    2.f.seek(3) # 是按照字节定光标的位置
    3.f.tell() #告诉你光标的位置
      print(f.tell())
    4.content = f.read()
      print(content)
      f.tell()

     5.f.readable() # 是否可读

       line = f.readline() # 一行一行的读
    
     line = f.readlines()  # 每一行当成列表中的一个元素,添加到list中
    6.在原文件中截取读取
    f.truncate(4)   
    7.循环读取,
    for line in f: 
         print(line)
     f.close()


  • 相关阅读:
    workflow里xaml格式(备忘)
    Excel 读取
    自定义工作流活动的外观的两种方式(补充)
    用SQLite,Enterprise的报错
    WF 4.0
    升级 90天 vs2008 在win2008下。
    NUnitLite web下的用法
    screen常用方法 Lei
    中文摘要的写法 Lei
    bootstrap, boosting, bagging 几种方法的联系 Lei
  • 原文地址:https://www.cnblogs.com/zzy-9318/p/8111071.html
Copyright © 2020-2023  润新知