• day007|python基础回顾7


    文件处理

    1 文件打开模式补充

    with open('a.txt', mode='r+t', encoding='utf-8') as f:
        print(f.read())
        print(f.writable())
        print(f.readable())
        f.write("你好")
    
    with open('a.txt', mode='w+t', encoding='utf-8') as f:
        print(f.writable())
        print(f.readable())
        f.write("你好")
        res = f.read()
        print("===> %s" % res)
    
    with open('a.txt', mode='a+t', encoding='utf-8') as f:
        print(f.writable())
        print(f.readable())
        print(f.read())
    
    f.flush()
    print(f.name)
    print(f.encoding)
    

    2.1 文件操作之读操作

    with open('a.txt', mode='rt', encoding='utf-8') as f:
        line1 = f.readline()
        print(line1)
        line2 = f.readline()
        print(line2)
    
        for line in f:
            print(line)
    
        lines = f.readlines()
        print(lines)
    

    2.2 文件操作之写操作

    with open('a.txt', mode='wt', encoding='utf-8') as f:
        f.write("1111
    2222
    3333
    ")
    
        for x in "hello":
            f.write(x)
    
        f.writelines("hello")  # f.write("hello")
    
        f.writelines(["111", "222", "333"])
        f.writelines(["111
    ", "222
    ", "333
    "])
    

    3 控制文件指针移动

    3.1 前提

    • 文件内指针移动,除了t模式下的read(n)中n代表的是字符个数

    • 其他都是以bytes为单位的

    with open('a.txt', mode='rt', encoding='utf-8') as f:
        res = f.read(6)
        print(res)
    
    with open('a.txt', mode='rb') as f:
        res = f.read(8)
        print(res)
        print(res.decode('utf-8'))
    
    with open('a.txt', mode='r+', encoding='utf-8') as f:
        f.truncate(8)
    

    3.2 f.seek()

    • f.seek(移动的字节个数,模式)

    • 三种模式

      0:参照文件开头移动指针

      1:参照当前所在的位置移动指针

      2:参照文件末尾位置移动指针

    • 只有0模式可以在t下使用,1和2只能在b下使用

    with open('a.txt', mode='a+b') as f:
        print(f.tell())         # 查看指针在文件的第几个字节
    
    with open('a.txt', mode='r+b') as f:
        f.seek(0, 2)
        print(f.tell())
    
    with open('a.txt', mode='a+b') as f:
        f.seek(-6, 2)
        # print(f.read().decode('utf-8'))
        print(f.read(3).decode('utf-8'))
    
    
    import time
    
    with open('a.txt', mode='rb') as f:
        f.seek(0, 2)
        while True:
            line = f.readline()
            if len(line) == 0:
                time.sleep(0.1)
            else:
                print(line.decode('utf-8'), end="")
    

    4 文件修改的两种方式

    4.1 方式一

    1、以r模式打开源文件,将源文件内容全部读入内存

    2、在内存中修改完毕

    3、以w模式打开源文件,将修改后的内容写入源文件

    优点:不必大量占用硬盘资源

    缺点:耗内存,需要足够的内存空间

    with open('a.txt', mode='rt', encoding='utf-8') as f1:
        data = f1.read()
        res = data.replace('hello', '早上好')
    with open('a.txt', mode='wt', encoding='utf-8') as f2:
        f2.write(res)
    

    4.2 方式二

    1、以r模式打开源文件,然后以w模式打开一个临时文件

    2、从源文件中读一行到内存中,修改完毕后直接写入临时文件,循环往复直到操作完毕所有行

    3、删除源文件,将临时文件名改为源文件名

    优点:没有对内存造成过度的占用

    缺点:需要硬盘预留出足够的空间来存放临时文件

    import os
    with open('a.txt', mode='rt', encoding='utf-8') as src_f,
            open('.a.txt.swp', mode='wt', encoding='utf-8') as dst_f:
    
        for line in src_f:
            dst_f.write(line.replace('你好', 'Hello'))
    
    os.remove('a.txt')
    os.rename('.a.txt.swp', 'a.txt')
    

    5 函数的基本使用

    5.1 概述

    1、什么是函数?
    函数就是用来盛放代码的容器

    ​ 具备某一功能的工具-->工具
    ​ 事先准备好工具的过程-->函数的定义
    ​ 遇到应用场景,拿来就用-->函数的调用

    2、为何要用函数?
    解决问题
    Ⅰ 可读性差
    Ⅱ 拓展性差
    3、如何用函数?
    先定义后引用

    5.2 基本使用

    def say_hello():  # say_hello=函数的内存地址
        print("======")
        print("hello world")
        print("======")
    
    print(say_hello)  # <function say_hello at 0x00000241DA0273A0>
    say_hello()
    
    x = 10            # x=10的内存地址
    print(x)
    

    5.3 步骤

    # 函数定义阶段:只检测语法,不执行代码
    # def foo():
    #     xxx
    #     print('from foo')
    
    # 函数调用阶段:执行函数体代码
    # foo()
    

    5.4 示例

    # 示例1
    def bar():
        print('from bar')
    
    def foo():
        print('from foo')
        bar()
    
    foo()
    
    # 示例二
    def bar():
        print('from bar')
        foo()
    
    def foo():
        print('from foo')
    
    bar()
    
    示例三
    def bar():
        print('from bar')
        foo()
    
    bar()
    
    def foo():
        print('from foo')
    

    5.5 函数定义的完整语法

    • def 函数名(参数1, 参数2, 参数3...):
      '''
      注释信息
      '''
      代码1
      代码2
      代码3
      return 返回值

    • 定义函数的三种形式

    无参函数
    def f1():
        print("hello")
        print("你好")
        print("Hi")
    f1()
    
    def login():
        name = input('username>>>:').strip()
        pwd = input('password>>>:').strip()
        if name == "ccc" and pwd == '111':
            print('ok')
        else:
            print('error')
    
    login()
    
    有参函数
    def login(name,pwd):
        if name == "ccc" and pwd == "123":
            print('ok')
        else:
            print('error')
    
    login("ccc","123")
    login("ccc","1234")
    
    def f2(x, y):
        print(x)
        print(y)
    
    f2(111, 222)
    
    def add(x, y):
        print(x+y)
    
    add(10, 20)
    add(30, 40)
    
    空函数
    def login():
        pass
    def transfer():
        pass
    def withdraw():
        pass
    def check_balance():
        pass
    
    • 调用函数的三种形式
    def add(x, y):
        z = x + y
        return z
    
    # res = add(10, 20)
    # print(res)
    # res = len("hello")
    # print(res)
    # 1、语句形式
    len("hello")
    
    # 2、表达式形式
    res = len("hello") + 10
    print(res)
    
    # 3、函数调用可以当作一个参数传给另外一个函数
    print(add(5, 5))
    
    res = add(add(1, 2), 3)
    print(res)
    

    5.6 函数的返回值

    • return作用1:控制返回值
    Ⅰ 没有return-->默认返回就是None
    def func():
        print(111)
    
    res = func()
    print(res)
    
    Ⅱ return 值-->返回就是那一个值
    def max2(x, y):
        if x > y:
            return x
        else:
            return y
    
    res = max2(100, 200) * 5
    print(res)
    
    Ⅲ return 值1,值2,值3--->返回的是一个元组
    def func():
        return [11, 22], 2, 3
    
    res = func()
    print(res, type(res))       # ([11, 22], 2, 3) <class 'tuple'>
    
    • return作用2:函数内可以有多个return,但只要执行一个就会立即种植函数的运行,并且会将return后的值当做本次调用的产品返回
    def func():
        print(111)
        return 2201202
        print(2222)
        return 11112222
        print(3333)
    
    res = func()
    print(res)          # 111 2201202
    

    附录:a.txt

    早上好玛卡巴卡
    早上好汤姆波利伯
    早上好小点点
    早上好依古比古
    早上好唔西迪西
    早安哈呼呼
    早安鸟儿
    Hello叮叮车
    Hello飞飞鱼
    
  • 相关阅读:
    常用正则表达式应用
    iOS 通知推送APNS
    IOS生活圈开发练习记录
    [转]定时器
    JavaScript如何在webView跳转到指点的位置
    用imageNamed加载图片产生的问题
    如何再分类中添加属性
    CADisplayLink定时器
    自定义UIBtton类后,在@implementation重写方法的作用
    CAAnimationGroup(组合动画)创建
  • 原文地址:https://www.cnblogs.com/caojiaxin/p/14039425.html
Copyright © 2020-2023  润新知