zoukankan      html  css  js  c++  java
  • python ( 进阶 第一部 )

    目录

    列表的相关操作与函数

    字符串的相关操作与函数

    集合相关操作与函数

    字典相关操作与函数

    深浅拷贝

    文件操作

    列表的相关操作

    列表的拼接

    lst1 = [1,2,3]
    lst2 = [4,5,6,6]
    res = lst1 + lst2
    print(res)

    列表的重复

    res = lst1 * 3
    print(res)

    列表的切片

    语法: [开始索引:结束索引:间隔值]

    [:] 或 [::] 截取所有列表

    列表的修改

    lst = ["吕洞宾","何仙姑","铁拐李","曹国舅","张果老","蓝采和","韩湘子","王文"]
    lst[3:5] = ["往返","晏国彰","牧树人"]
    print(lst)

    利用切片可以一次修改多个元素,没有数量上的限制

    切片匹配和步长(间隔值),切出多上个元素,修改多少个元素.

    列表的删除

    lst = [“吕洞宾”,“何仙姑”,“铁拐李”,“曹国舅”,“张果老”,“蓝采和”,“韩湘子”,“王文”]
    del lst[-1]
    print(lst)
    #删除列表的元素
    
    lst = [“吕洞宾”,“何仙姑”,“铁拐李”,“曹国舅”,“张果老”,“蓝采和”,“韩湘子”,“王文”]
    res = lst[-1]
    del res
    print(lst)
    #删除的是变量res本身,不是列表中的元素

    列表的相关函数

    lst = ['123"]
    
    #1 .append 向列表的末尾追加一个新的元素
    lst.append('你好')
    print(lst)
    
    
    #2 .insert 自定索引添加元素
    lst.insert(0,'流云')
    print(lst)
    
    #3 .extend 迭代追加所有元素
    lstvar= '99'
    lst.extend(lstvar)
    print(lst)

    # pop 通过索引删除元素,若没有索引默认移除最后一个元素
    lst = ["晏国彰","毛洪磊","刘子涛","刘聪","牧树人"]
    res = lst.pop(1)
    res = lst.pop()
    print(res)
    print(lst)
    
    
    # remove  通过给定的元素进行删除,如果有多个元素,默认删除第一个
    lst = ["晏国彰","毛洪磊","刘子涛","刘聪","牧树人","刘子涛","刘子涛"]
    lst.remove("刘子涛")
    print(lst)
    
    
    # clear 清空列表
    lst = ["晏国彰","毛洪磊","刘子涛","刘聪","牧树人","刘子涛","刘子涛"]
    lst.clear()
    print(lst)

    改, 查 ( 参考列表的相关操作 )

    列表的其他函数

    index 获取某个值在列表中的索引

    列表.index(值[start][end])   #[ ] 表达参数可选项,找不到报错

    lst = ["晏国彰","毛洪磊","刘子涛","刘聪","牧树人","刘子涛","刘子涛"]
    res = lst.index("刘子涛")
    res = lst.index("刘子涛",3)
    res = lst.index("刘子涛",3,5) error
    print(res)

    count  计算某个元素出现的次数(不可划分范围)

    lst = ["晏国彰","毛洪磊","刘子涛","刘聪","牧树人","刘子涛","刘子涛"]
    res = lst.count("刘子涛")
    print(res)

    sort() 列表排序

    从小到大排列
    lst = [44,99,1,10,3,-5,-90]
    lst.sort()
    从大到小排列
    lst.sort(reverse=True)
    print(lst)

    reverse()  列表反转

    reverse() 列表反转操作
    lst = ["王文","刘德华","郭富城","张学友"]
    lst.reverse()
    print(lst)

    字符串的相关操作

    字符串的拼接

    strvar = "今天是" + "星期一"
    strvar += ",今天非常开心"
    print(strvar)

    字符串的跨行拼接

    strvar = "sdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdf" \
    "多余的几行放在第二行进行显示"
    print(strvar)

    字符串的重复

    strvar = "重要的事情说三遍" * 3
    print(strvar)

    字符串的切片

    语法: 字符串{::]完整格式:  [start:end:间隔值]

    [:] 或[::] 截取所有字符串

    formate 填充符的使用 ( ^<>)

    1. ^原字符串居中  >原字符串居右,  <原字符串居左

    2. {who:^10}

      who:关键字参数,:要填充的字符,^:原字符串居中

      10:总长度 = 原字符串长度 + 填充字符串长度

    strvar = "{who:*^10}在{where:>>10},{do:!<10}".format(who="刘鹏",where="电影院",do="拉屎")
    print(strvar)

    3. 特殊站位符的使用( :d  :f    :s    :,)

    :d 整型站位符(要求类型必须是整型)

    strvar = "刘子豪昨天买了{:d}个花露水".format(100) # 100.5error
    print(strvar)

    # :2d 占用俩位, 不够俩位空格来补,默认居右
    strvar = "刘子豪昨天买了{:2d}个花露水".format(3)

    :f 浮点数占位符(要求必须是浮点数)

    strvar = "刘心毕业时,找工作的薪资是{:f}".format(2.5)
    
    #:2f  小数点保留俩位
    
    strvar = "刘心毕业时,找工作的薪资是{:.2f}".format(2.56789)
    print(strvar)

    :s  字符串占位符 (要求必须是,字符串)

    strvar = "{:s}".format("今天天气不错,万里无云")
    print(strvar)

    :, 金钱站位符

    strvar = "{:,}".format(123456789)
    print(strvar)

    综合案例:

    strvar = "{}向{}开了一枪,银弹而亡".format("李志辉","明浩")
    print(strvar)

    字符串的格式化 formate

    顺序传参

    strvar = "{}向{}开了一枪,银弹而亡".format("李志辉","明浩")
    print(strvar)

    索引传参

    strvar = "考试时{1},游戏时{0}".format("唯唯诺诺","重拳出击")
    print(strvar)

    关键字传参

    strvar = "{who2}甩了一个飞吻,{who1}神魂颠倒".format(who1="刘彩霞",who2="马生平")
    print(strvar)

    容器类型数据(列表元组)传参

    strvar = "{1[2]}向{0[0]}抛了一个媚眼,鼻血直冒三万多尺,失血而亡".format(["孙翔群","曹晨光","宋云杰"],("李亚","孙致和","温子月"))
    print(strvar)

    format当中,不可以使用逆向下标,不识别

    strvar = "{group2[0]}向{group1[-1]}抛了一个媚眼,鼻血直冒三万多尺,失血而亡".format(group1 = ["孙翔群","曹晨光","宋云杰"],group2 = ("李亚","孙致和","温子月"))
    print(strvar)

    如果容器是字典,直接写值,不需要加上引号

    strvar = "{group1[ccg]}向{group2[1]}抛了一个媚眼,鼻血直冒三万多尺,失血而亡".format(group1 = {"kxq":"孙翔群","ccg":"曹晨光","syj":"宋云杰"},group2 = ("李亚","孙致和","温子月"))
    print(strvar)

    字符串的相关函数

    capitalize 每个单词的首字母大写

    strvar = "how old are you"
    res = strvar.capitalize()
    print(res)

    title 句首字母大写

    strvar = "how old are you"
    res = strvar.title()
    print(res)

    upper 所有字母都大写

    strvar = "to be or not to be that is a question"
    res = strvar.upper()
    print(res)

    lower  所有字母都小写

    strvar = "to be or not to be that is a question"
    res = strvar.lower()
    print(res)

    swapcase  大小写互换

    strvar = "I Love You"
    res = strvar.swapcase()
    print(res)

    len 计算字符串长度

    strvar = "adfs234sdfsa"
    res = len(strvar)
    print(res)

    count 统计字符串某个元素的数量

    strvar = "adfs234sdfsa"
    res = strvar.count("a")
    print(res)

    find 查找某个元素第一次出现的索引位置   (推荐使用)  字符串.find('元素':start:end) 如果找不到返回-1

    strvar = "oh Father this is my Favorate dog"
    res = strvar.find("F")
    res = strvar.find("F",4)
    res = strvar.find("Fav",5,10) # 结束索引本身取不到,取到之前的那个值
    print(res)

    index与find功能相同 .find找不到直接报错

    res = strvar.index("Fav",5,10) error

    startswith 判断是否以某个元素开头   字符串.startswith('元素',start ,end ) 存在返回True 否则返回False

    strvar = "oh Father this is my Favorate dog"
    res = strvar.startswith("oh")
    res = strvar.startswith("this",10)
    res = strvar.startswith("this",10,13) # 10 11 12
    print(res)

    endswith  判断是否以某个元素结尾    

    res = strvar.endswith("dog")
    res = strvar.endswith("rate",-12)
    res = strvar.endswith("rate",-12,-4)
    print(res)

    isupper  判断 字符串是否都是大写

    res = strvar.isupper()
    print(res)

    islower  判断字符串是否都是小写

    strvar = "abcdd12345"
    res = strvar.islower()
    print(res)

    isdecimal  判断字符串是否是纯数字

    strvar = "12354"
    strvar = "12354.8979112"
    res = strvar.isdecimal()
    print(res)

    ljust  填充字符串,原字符串居左 (默认填充空格)

    strvar = "abc"
    res = strvar.ljust(10)
    print(res)

    rjust  填充字符串,原字符串居右 (默认填充空格)

    strvar = "abc"
    res = strvar.rjust(10,"&")
    print(res)

    center 填充字符串,原字符串居中  (默认填充空格)

    strvar = "abc"
    res = strvar.center(10) # 原字符串长度 + 填充字符长度 = 10 ,默认填充空格
    res = strvar.center(10,"#")
    print(res)

    strip  默认去掉收尾俩边的空白符

    strvar = "@@@@@ 周杰伦           @@@@@"
    res = strvar.strip()
    res = strvar.strip("@") # 指定去掉的符号
    print(res)
    
    strvar = "@@@@@ 周杰伦           @@@@@"
    #rstrip 去掉右边某个字符 
    print(  strvar.rstrip("@")   )
    #lstrip 去掉左边某个字符 
    print(  strvar.lstrip("@")   )

    split 按某字符将字符串分割成列表(默认分割字符是空格)

    strvar = "you can you up no can no bb"
    lst = strvar.split()
    strvar = "you-can-you-up-no-can-no-bb"
    lst = strvar.split("-")   # 从左到右分隔
    lst = strvar.rsplit("-",2)# 从右到左分隔,(可以指定分隔的次数)
    print(lst)

    join 按某字符将列表拼接成字符串(容器类型的都可以)

    lst = ['you', 'can', 'you', 'up', 'no', 'can', 'no', 'bb']
    res = "-".join(lst)
    print(res)

    replace 替换 ,把字符串的旧字符换成新字符  replace(要替换的元素,替换成的元素,替换的次数)

    strvar = "可爱的小青蛙喜欢吃蚊子,有没有,有没有,还有没有"
    res = strvar.replace("有没有","真没有")
    res = strvar.replace("有没有","真没有",1)
    print(res)

    集合相关操作与函数

    集合相关的操作

    intersection()   交集  &

    set1 = {"jacklove","theshy","rookie","xboyww"}
    set2 = {"倪萍","张国荣","赵本山","刘能","赵四","xboyww"}
    res = set1.intersection(set2)
    print(res)
    简写 &
    res = set1 & set2
    print(res)

    difference()  差集   -

    set1 = {"jacklove","theshy","rookie","xboyww"}
    set2 = {"倪萍","张国荣","赵本山","刘能","赵四","xboyww"}
    res = set1.difference(set2)
    print(res)
    简写
    res = set1 - set2
    print(res)

    union()   并集 |

    set1 = {"jacklove","theshy","rookie","xboyww"}
    set2 = {"倪萍","张国荣","赵本山","刘能","赵四","xboyww"}
    res = set1.union(set2)
    print(res)
    简写 |
    res = set1 | set2
    print(res)

    symmetric_difference()    对称差集

    set1 = {"jacklove","theshy","rookie","xboyww"}
    set2 = {"倪萍","张国荣","赵本山","刘能","赵四","xboyww"}
    res = set1.symmetric_difference(set2)
    print(res)
    简写 ^
    res = set1 ^ set2
    print(res)

    isubset()  判断是否是子集

    set1 = {"周杰伦","王力宏","罗志祥","潘玮柏"}
    set2 = {"周杰伦","王力宏"}
    res = set1.issubset(set2)
    print(res)
    简写 < 
    res = set1 < set2
    print(res)

    issuperset()  判断是否是父集

    set1 = {"周杰伦","王力宏","罗志祥","潘玮柏"}
    set2 = {"周杰伦","王力宏"}
    res = set1.issuperset(set2)
    print(res)
    简写
    res = set1 > set2
    print(res)

    isdisjoint()   检测俩个集合是否不相交

    set1 = {"周杰伦","王力宏","罗志祥","潘玮柏"}
    set2 = {"周杰伦","王力宏"}
    res = set1.isdisjoint(set2)
    print(res)

    集合相关函数

    .add( 向集合中添加元素( 一次加一个)

    setvar = {"神秘男孩","金角大王"}
    setvar.add("银角大王")
    print(setvar)

    .update()  迭代添加元素( 一次加一堆)

    setvar = {"神秘男孩","金角大王"}
    strvar = ("刘子豪","刘鑫")
    setvar.update(strvar)
    print(setvar)

    pop() 随机删除集合中的一个元素

    setvar = {"神秘男孩","金角大王"}
    res = setvar.pop()
    print(res , setvar)

    clear() 清空集合

    setvar = {"神秘男孩","金角大王"}
    setvar.clear()
    print(setvar)

    remove()  删除集合中指定的值( 不存在时会报错)  了解

    strvar = ("刘子豪","刘鑫")
    setvar.remove("神秘男孩")
    print(setvar)

    discard()   删除集合中指定的值( 不存在时不报错) 推荐使用

    setvar.discard("神秘男孩")
    setvar.discard("神秘男孩1234324")
    print(setvar)

    .forzenm  set()  可强转容器类型数据变为冰冻集合   冰冻集合一旦创建,不能进行任何修改,只能做交差并补操作

    lst1 = ["王闻",18,"男性","爱好:跑步"]
    fz1 = frozenset(lst1)
    
    lst2 = ("王闻","地址:包头","买一辆特斯拉9.9包邮")
    fz2 = frozenset(lst2)
    print(fz1 , type(fz1))
    print(fz2 , type(fz2))
    #不能够在冰冻集合当中添加或者删除元素
    #fz1.add(123) error
    #只能交差并补
    print(  fz1 & fz2 )
    print(  fz1 - fz2 )

     

    字典相关操作与函数

    方式一:

    dic = {}
    dic[“ww”] = “一表人才,除了帅气的皮囊之外,一无所有”
    dic[‘ywz’] = “渣男”
    dic[“hxl”] = “抠脚老汉”
    print(dic)

    方式二:

    fromkeys() 使用一组键和默认值创建字典
    lst = ["ww","ywz","hxl"]
    dic = {}.fromkeys(lst,None)
    print(dic)

    注意点: 三个键所指向的列表是同一个(不推荐使用方式二)

    lst = ["ww","ywz","hxl"]
    dic = {}.fromkeys(lst,[])
    print(dic)
    dic["ww"].append(1)
    print(dic)
    
    dic["ww"] = []
    dic['ywz'] =[]
    dic["hxl"] =[]

    pop( ) 通过键去删除键值对( 若没有该键可设置默认值,预防报错)

    dic = {"top":"花木兰" , "middle":"甄姬" , "bottom":"孙尚香" ,  "jungle" : "钟馗" , "support":"蔡文姬" }
    res = dic.pop("top")
    # 如果删除的是不存在的键,直接报错
    # res = dic.pop("top123")
    # 可以设置默认值,防止报错
    # res = dic.pop("top123","没有这个键")
    res = dic.pop("middle","没有这个键")

    popitem()  删除最后一组键值对

    dic = {"top":"花木兰" , "middle":"甄姬" , "bottom":"孙尚香" ,  "jungle" : "钟馗" , "support":"蔡文姬" }
    res = dic.popitem()
    print(res, dic)

    clear(()  清空字典

    dic.clear()

    print(dic)

    #update() 批量更新(有该键就更新,没该键就添加)
    dic = {'ww': '一表人才,除了帅气的皮囊之外,一无所有', 'ywz': '渣男', 'hxl': '抠脚老汉'}
    dic_new = {"ywz":"暖男","hxl":"扣手","ly":"小美女,单纯,可爱,活泼,灵巧...."}
    
    # 方法一(推荐)
    dic.update(dic_new)
    print(dic)
    
    # 方法二
    dic.update(kxq="聪明,活泼,可爱,灵巧,惹人喜欢",ccg="乐观,大方,可爱,灵巧")
    print(dic)

    #get()    通过键获取值(若没有该键可设置默认值,预防报错)
    dic = {'ww': '一表人才,除了帅气的皮囊之外,一无所有', 'ywz': '暖男', 'hxl': '扣手'}
    res = dic.get("ww")
    res = dic.get("zbcdefg") # None
    res = dic.get("zbcdefg","没有这个键")
    # res = dic['abcee'] error
    print(res)

    字典重点函数

    dic = {'ww': '一表人才,除了帅气的皮囊之外,一无所有', 'ywz': '暖男', 'hxl': '扣手'}
    #keys()   将字典的键组成新的可迭代对象
    res = dic.keys()
    print(res)
    
    #values() 将字典中的值组成新的可迭代对象
    res = dic.values()
    print(res)
    
    #items()  将字典的键值对凑成一个个元组,组成新的可迭代对象 
    res = dic.items()
    print(res)

    深浅拷贝

    a = 15
    b = a
    a = 16
    print(b)
    
    lst1 = [1,2,3]
    lst2 = lst1
    lst1.append(4)
    print(lst2)
    
    
    
    #浅拷贝
    import copy
    lst1 = [1,2,3]
    # 方法一 copy.copy 模块.方法
    lst2 = copy.copy(lst1)
    
    lst1.append(4)
    print(lst1)
    print(lst2)
    
    
    # 方法二  列表.copy()
    lst1 = [1,2,3,4]
    lst3 = lst1.copy()
    lst1.insert(0,0)
    print(lst1)
    print(lst3)
    
    
    
    #深拷贝
    import copy
    lst1 = [1,2,3,[4,5,6]]
    lst2 = copy.copy(lst1)
    lst1[-1].append(7)
    lst1.append(100)
    print(lst1)
    print(lst2)
    
    lst1 = [1,2,3,[4,5,6]]
    lst2 = copy.deepcopy(lst1)
    # lst1[-1].extend("ab")
    print(lst2)
    print(lst1)
    print(id(lst2[-1]))
    print(id(lst1[-1]))
    
    print(id(lst1[0]))
    print(id(lst2[0]))
    
    lst2[0] = 1111
    print(id(lst1[0]))
    print(id(lst2[0])

    总结:

    (1) 浅拷贝只拷贝一级容器的所有数据

    深拷贝拷贝所有层级的所有数据

    浅拷贝速度比深拷贝速度快

    深拷贝在执行时,如果是不可变数据,地址会暂时的指向原来数据

    如果是可变数据,直接开辟新的空间

    不可变数据 Number str tuple

    可变数据 ;list  set dic 

    文件操作

    格式:

    fp = open (“文件名”,node = “模式”,encoding=‘utf-8")
    fp->文件的io对象(文件名柄)
    i => input 输入
    o => output 输出

    文件的写入

    # 1.打开文件
    fp = open("ceshi1.txt",mode="w",encoding="utf-8") # 
    
    # 2.写入内容
    fp.write("把大象塞进去") # 把大象放进去
    
    # 3.关闭文件
    fp.close() # 把冰箱门关上

    文件的读取

    # 1.打开文件
    fp = open("ceshi1.txt",mode="r",encoding="utf-8") 
    
    # 2.读取内容
    res = fp.read() # 把大象拿出来
    print(res)
    
    # 3.关闭文件
    fp.close() # 把冰箱门关上

    字节流的转换

    1. bytes:是用来传输或者存储的数据格式      b’1234’ b"abcd" b"我爱你" -> b开头的字节流,范围只能是ascii编码

    2. 如果是中文使用encode 和 decode 来进行转换    将字符串和字节流(Bytes流)类型进行转换 (参数写成转化的字符编码格式)

    3. encode()   编码将字符串转化为字节流(bytes流)

    4. decode()   解码  将bytes流转化为字符串

    5. a  = b'1234'      print(a,type(a))

    strvar = "我爱你"
    # encode 编码 -> 变成二进制字节流
    res = strvar.encode("utf-8")
    print(res , type(res))
    
    # decode 解码 =>二进制字节流恢复成原来的字符串
    res2 = res.decode("utf-8")
    print(res2 , type(res2))

    6. len可以计算字节个数

      num= len(res)

      printnum)

    7. 一个中文占用3个字节,通过decode 反解出爱这个自

      res3 =b"\xe7\x88\xb1".decode(“utf-8”)

      print(res3)

    8. 例题:

    #  程序员的表白方式
    strvar = "我!是你一辈子也得不到的男人"
    strvar2 = strvar.encode()
    print(strvar2)
    
    # 四.存储二进制字节流
    """不需要指定encoding编码集,否则报错"""
    fp = open("ceshi2.txt",mode="wb")
    fp.write(strvar2)
    fp.close()
    
    # 五.读取二进制字节流
    fp = open("ceshi2.txt",mode="rb")
    res = fp.read()
    fp.close()
    
    print(res)
    # 通过decode反解出字符串
    strvar = res.decode()
    print(strvar)
    
    # 六.复制图片
    """图片,音频,视频"""
    # 1.读取原图片所有的内容
    fp = open("集合.png",mode="rb")
    res = fp.read()
    fp.close() 
    
    # 2.把读取的内容存储到另外一个文件
    # fp = open("集合2.png",mode="wb")
    # 指定绝对路径(完整路径)
    fp = open(r"E:\python31\day8\集合3.png",mode="wb")
    fp.write(res)
    fp.close()

    文件的扩展模式

    1. (utf-8编码格式下  默认一个中文占三个字节,一个英文符号,占用一个字节)

      read()   功能 : 读取字符的个数(里面的参数代表字符个数)

      seek()   功能    调整指针的位置(里面的参数代表字节的个数)

      tell()    功能    当前光标左侧所有的字节数

    2. seek(0)  直接把光标移动到文件开头

     seek(0,2)  直接把光标移动到文件末尾

    r+模式

    # r+ 先读后写
    fp = open("ceshi3.txt",mode="r+",encoding="utf-8") 
    # 先读
    res = fp.read()
    print(res)
    
    # 后写
    fp.write("1234")
    
    # 在读
    fp.seek(0) # 调整光标位置在开头
    res = fp.read()
    print(res)
    fp.close()
    
    
    # r+ 先写后读
    fp = open("ceshi3.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("ceshi4.txt",mode="w+",encoding="utf-8")
    fp.write("abc")
    
    
    fp.seek(0)
    res = fp.read()
    print(res)
    fp.close()

    a+模式

    fp = open("ceshi5.txt",mode="a+",encoding="utf-8")
    fp.write("123")
    
    fp.seek(0)
    res = fp.read()
    print(res)
    
    # a模式在写入内容时,会强制把光标移动到最后
    fp.seek(1)
    fp.write("abc")
    fp.close()

    4. 如果r模式内,区别a模式

    fp = open("ceshi5.txt",mode="r+",encoding="utf-8")
    fp.seek(1)
    fp.write("abc")
    fp.close()

    5. read  seek  tell  三个函数的使用

    fp = open("ceshi6.txt",mode="r+",encoding="utf-8")
    res = fp.read(3)
    print(res)
    
    fp.seek(6)
    print(fp.read(1))

    6. 计算文件指针在左侧所有的字节数

    res = fp.tell()
    print(res)
    fp.close()

    7. 注意点: seek 移动中文字节的时候,有可能报错

    fp = open("ceshi6.txt",mode="r+",encoding="utf-8")
    fp.seek(2)
    res = fp.read()
    print(res)
    fp.close()
    
    # print("我".encode())
    # b'\xe6\x88\x91'

    8. with语法的使用 ( close 操作with语法可以自动实现)

    with open("集合.png",mode="rb") as fp:
     res = fp.read()
    
    with open(r"E:\python31\day8\集合4.png",mode="wb") as fp:
     fp.write(res)
    
    with open(r"E:\python31\day8\集合4.png",mode="wb") as fp:
     fp.write(res)

    文件关闭的意义

    1,. 刷新缓存区 flush

      当文件关闭的时候自动刷新缓存区

      当整个程序运行结束的时候自动刷新缓存区

      当缓存区写满了 ,会自动刷新缓存区

    2. 手动刷新缓存区

    fp = open("ceshi6.txt",mode="r+",encoding="utf-8")
    fp.write("zzz")
    # 手动把缓冲区里面的内容写入文件当中
    fp.flush()
    while True:
        pass
    fp.close()

    3. 文件的相关函数

    fp = open(“ceshi6.txt”,mode=“a+”,encoding=“utf-8”)
    #readable() 功能: 判断文件对象是否可读
    res = fp.readable()
    print(res)
    #writable() 功能: 判断文件对象是否可写
    res = fp.writable()
    print(res)

    4. readine()  功能: 读取一行文件内容

      参数> 当前行字符总个数=>  以当前行读取

      参数< 当前行字符总个数=> 以参数的大小来读取字符的个数

    5. 默认读取readine  读取一行

    """
    with open("ceshi7.txt",mode="r+",encoding="utf-8") as fp: 
     # res = fp.readline(3000)
     # print(res) 
     # 文件对象fp也是一个可迭代对象
     '''在遍历文件对象的时候,默认一次拿一行'''
     for i in fp:
      print(i)
    # 读取所有内容
    with open("ceshi7.txt",mode="r+",encoding="utf-8") as fp: 
     # 先读取一行
     res = fp.readline()
     # 判断是不是空
     while res:
      print(res)
      res = fp.readline()
    """
    #readlines()    功能:将文件中的内容按照换行读取到列表当中
    lst_new = []
    with open("ceshi7.txt",mode="r+",encoding="utf-8") as fp: 
     lst = fp.readlines()
     # print(lst) # ['\t窗前明月光\n', '疑是鞋两双\t\t\n', '\t\t举头王明月\n', '\t低头看裤裆']
     for i in lst:  
      lst_new.append(i.strip())
    print(lst_new)  # ['窗前明月光', '疑是鞋两双', '举头王明月', '低头看裤裆']
    #writelines()   功能:将内容是字符串的可迭代性数据写入文件中 参数:内容为字符串类型的可迭代数据
    """可迭代型数据(容器类型数据,range对象,迭代器)"""
    """
    lst = ["春眠不觉晓\n","处处蚊子咬\n","夜来大狗熊\n","一个也跑不了\n"]
    # lst = [1,2,3,4] error
    with open("ceshi8.txt",mode="w",encoding="utf-8") as fp:
     fp.writelines(lst)
    """
    #truncate()     功能: 把要截取的字符串提取出来,然后清空内容将提取的字符串重新写入文件中 (字节)
    with open("ceshi8.txt",mode="r+",encoding="utf-8") as fp:
     fp.truncate(3)
    while " ":
     print(123)
    好好学习,天天向上。
  • 相关阅读:
    java 编程语言基础 第一章 自我介绍
    Spring详解(四)------注解配置IOC、DI
    Spring详解(三)------DI依赖注入
    Spring详解(一)------概述
    mybatis 详解(十一)------ mybatis和spring整合
    mybatis 详解(十)------ 逆向工程
    mybatis 详解(九)------ 一级缓存、二级缓存
    mybatis 详解(八)------ 懒加载
    mybatis 详解(七)------一对一、一对多、多对多
    06-单例模式
  • 原文地址:https://www.cnblogs.com/liuun/p/13876944.html
Copyright © 2011-2022 走看看