zoukankan      html  css  js  c++  java
  • day3

    重点:

    • 强制把数据写入硬盘刷新:flush()函数(sys库中)。内存和缓存中的数据,是以块的形式写入硬盘,有时代码执行了,但是实际并没有把结果写入硬盘,若电脑断电或重启将丢失数据。
    • 编码要注意区分:*.py文件的编码,py文件里代码的编码
    • python3的中文默认编码是unicode
    • File文件里内容的修改,都要涉及到新File文件
    • python中函数没有返回结果,返回:None。1个返回结果,返回:对象object。多个返回结果,返回:元组tuple
    • 函数中参数:test(*args)表示接受N个位置参数,转成元组方式;test(*kwargs)表示接受N个关键字参数,转成字典的方式
    • 递归函数:要有明确的结束条件;问题规模每递归一次都应该比上一次的问题规模有所减少;效率低

    集合:

    list_1=[3,2,1,4,5,7,6,8,8,9,1,4,5,9]
    list_1=set(list_1) #设置为集合,得到元素集
    print(list_1,type(list_1))
    list_2=set([2,6,1,4,66,97,88])
    
    print(list_1,list_2)
    
    #交集
    print(list_1.intersection(list_2))
    #并集
    print(list_1.union((list_2)))
    #差集
    print(list_1.difference(list_2))
    print(list_2.difference(list_1))
    #是否为子集父集
    list_3=set([1,3,5])
    print(list_3.issubset(list_1))   #是否为子集
    print(list_1.issuperset(list_3)) #是否为父集
    #对称差集:两个集合并后取出交的
    print(list_1.symmetric_difference(list_2))
    View Code

    递归:

    def calc(n):
        print(n)
        if int(n/2) >0:
            return calc(int(n/2))
    
    calc(10)
    View Code

    进度条:

    import sys,time
    
    for i in range(50):
        sys.stdout.write("#")
        sys.stdout.flush()  #强制写入硬盘
        time.sleep(0.1)

    编码转换:

    #设置py文件编码为GBK,不是内部代码为GBK
    #-*- coding:GBK -*-
    s="你好"
    print(s)
    
    print(s.encode("GBK"))
    print(s.encode("utf-8"))
    print(s.encode("utf-8").decode("utf-8"))
    print(s.encode("utf-8").decode("utf-8").encode("gb2312"))
    print(s.encode("utf-8").decode("utf-8").encode("gb2312").decode("gb2312"))

    文件修改:

    f = open("FileTest", "r", encoding="utf-8")
    f_new = open("FileTest2", "w", encoding="utf-8")
    
    
    for line in f:
        if "ZhangYuan" in line:
            line=line.replace("ZhangYuan","ZhangTEST")
        f_new.write(line)
    f.close()
    f_new.close()

    with语句文件操作:

    #with语句可以自动关闭文件
    with open("FileTest","r",encoding="utf-8") as f1,open("FileTest2","r",encoding="utf-8") as f2:
        for line in f1:
            print(line)
        for line in f2:
            print(line)
    View Code

    正常文件操作:

    #-------------------以下.readlines()只适合读小文件-----------------------
    #data= open("FileTest",encoding="utf-8").read()
    #print(data)
    f=open("FileTest","r",encoding="utf-8")  #文件句柄,"r表示只读(默认)
    
    data=f.read()
    data2=f.read() #接着上面的位置继续读,不是重新读
    print(data)
    print('---------------------------')
    print(data2,"OK")   #上面的已经读完,所以没有内容
    
    g=open("FileTest","w",encoding="utf-8")  #文件句柄,"w"表示重头只写(重新写)
    g.write("ABCDEFGG
    ")
    g.write("abcdefrg
    ")
    g.write("ABCDEFGG
    ")
    g.write("abcdefrg
    ")
    g.write("My name is ZhangYuan
    ")
    g.write("abcdefrg
    ")
    g.write("123467
    ")
    g.write("7654321
    ")
    
    k=open("FileTest","a",encoding="utf-8")  #文件句柄,"a"表示末尾只写(尾部追加)
    k.write("TEST1")
    k.write("TEST2
    ")
    k.write("TEST3
    ")
    k.write("TEST4
    ")
    
    f.close()
    g.close()
    k.close()
    
    f=open("FileTest","r",encoding="utf-8")
    #可用循环方式逐行读取
    #for i in range(3):
    #    print(f.readline())
    
    print("--------我是分割线---------")
    R=f.readlines()
    print(R,"Finish")
    for index,line in enumerate(R):
        print(index,line.strip()) #直接print(line)包括空格和换行,用strip()可去除
    f.close()
    #-------------以上.readlines()只适合读小文件---------------------------
    
    #-------------------------以下适合大文件----------------------------------
    print("以下适合大文件")
    f=open("FileTest","r",encoding="utf-8")
    #每次读取只保存一行到内存,不会累积内存
    count=0
    for line in f:
        print(count,line,"不积累内存")
        count+=1
    f.close()
    #-------------------------以上适合大文件----------------------------------
    
    f=open("FileTest","r",encoding="utf-8")
    print(f.tell()) #按字符来计数返回file读取位置
    print(f.readline())
    print(f.tell()) #按字符来计数返回file读取位置
    f.seek(0) #光标回到0
    print(f.tell())
    
    print(f.encoding)#返回编码方式
    #强制刷新(确认下内存或缓存中的数据已经写入硬盘,有时候写入的数据会保存到缓存,出问题就不能保存在硬盘了)
    print(f.flush())
    
    #截断前20个字符保留,其余删除。不输入则全部清空
    '''
    f=open("FileTest","a",encoding="utf-8") #如果是"w",表示file以新文件打开,里面没有内容,截断内容只能用"a"
    f.truncate(20) #截断前20个字符保留(跟光标位置无关)
    f.close()
    '''
    
    #硬盘上File文件的写入都是覆盖原位置,所以不存在直接性的在指定光标位置写入,除非进一步处理
    #文件先读后写(追加)
    f=open("FileTest","r+",encoding="utf-8")
    print(f.readline())
    print(f.readline())
    f.write("
    ABCDEFG")
    f.close()
    '''
    #文件先写后读
    print("---先写后读---")
    f=open("FileTest","w+",encoding="utf-8")
    print(f.readline())
    f.close()
    
    #文件先追加后读
    f=open("FileTest","a+",encoding="utf-8")
    f.close()
    '''
    
    #以二进制方式
    print("---二进制---")
    f=open("FileTest","rb") #二进制不能传递encoding="utf-8"参数
    print(f.readline())
    print(f.readline())
    print(f.readline())
    g=open("FileTest","ab")
    g.write("
    Hello World
    ".encode())
    View Code

    函数操作1:

    #定义一个函数
    def function1():
        """testing1,注释最好写上"""
        print("you are in the Testing")
        return True
    
    #定义一个过程(没有返回值)
    #python中过程也有返回值None
    def function2():
        """Testing2"""
        print("you are in the Testing2")
    
    x=function1()
    y=function2()
    ###############################################
    import time
    def logger():
        time_format="%Y-%m-%d %X"
        time_current=time.strftime(time_format)
        with open("a.txt","a+") as f:
            f.write("%s end action
    " %time_current)
    
    def test1():
        "......"
        print("In the Test1")
        logger()
    
    def test2():
        "......"
        print("In the Test2")
        logger()
    
    def test3():
        "......"
        print("In the Test3")
        logger()
    
    test1()
    test2()
    test3()
    View Code
    def test(x,y=12,z=64):
        print("x=%s"%x)
        print("y=%s"%y)
        print("z=%s"%z)
    x=1
    y=2
    z=3
    print(test(3))
    View Code

    函数操作2:

    #没有返回结果,返回:None
    #1个返回结果,返回:对象object
    #多个返回结果,返回:元组tuple
    
    def test1():
        print("in the test1")
    def test2():
        print("in the test2")
        return 0
    def test3():
        print("in the test3")
        return 1,"Hello",["A","B","C"],{"name":"Angle"}
    def test4():
        print("in the test4")
        return test1()
    
    x=test1()
    y=test2()
    z=test3()
    out=test4()
    print(x,y,z)
    print(out)

     函数操作3:

    #*args:参数组传递,*表示接受的参数个数不固定
    #接受N个位置参数(不是关键字参数),转换成元组方式
    def test(*args):
        print(args)
    test(1,2,3,4,5)
    test(*[1,2,3,4,5,6])  #加*把列表变成元组
    
    #**kwargs:把N个关键字参数,转换成字典的方式
    #接受关键字参数
    def test2(**kwargs):
        print(kwargs)
    test2(name="ABC",age=12,sex="male")
    test2(**{"name":"BCDE","age":12,"Sex":"female"})
    
    def test3(name,**kwargs):
        print(name)
        print(kwargs)
    test3('ales',age=18,sex="male")
    
    def test4(name,age=18,**kwargs):
        print(name)
        print(age)
        print(kwargs)
    test4('abc',sex='m',hobby='testla')
    test4('abc',sex='m',hobby='testla',age=3)
    
    def test5(name,age=18,*args,**kwargs):
        print(name)
        print(age)
        print(args)
        print(kwargs)
        logger("Test5")
    
    #在一个函数里引用其他函数
    def logger(source):
        print("from %s"%source)
    
    test5("Test5",age=34,sex="m",hobby="Tesla")
    
    #局部变量
    def change_name(name):
        print("before change",name)
        name="ABCDE" #局部变量,只在函数内生效
        print("after change",name)
    
    name="musa"
    change_name(name)
    print("origianl name=",name)
    
    def change_name1(name1):
        global name#加入这个才可以在里面改全局的变量,加入global声明这个变量是全局的
        print("before change",name)
        name="ABCDE" #局部变量,只在函数内生效
        print("after change",name)
    
    change_name1(name)
    print("origianl name=",name)
    
    '''
    # 以下内容不要用,语法正确,但非常容易出错
    def change2():
        global A
        A="GFDSA"
    change2()
    print(A)
    '''
    
    #列表,字典,集合,类 都可以通过函数改
    school ="oldboy"
    names=["A","B","C"]
    def change2():
        print(names)
        names[0]="D"
        print(names)
    change2()
    print(names)
  • 相关阅读:
    iOS面试题及答案大总结
    iOS 画音频波形曲线 根据音频数据版
    iPhone-获取网络数据或者路径的文件名
    python语言使用yaml 管理selenium元素
    出现事故后我们怎么复盘分析
    如何提升测试质量,减少漏测
    robotframework环境搭建
    如何做ui自动化---步骤详解
    Jenkins报错Caused: java.io.IOException: Cannot run program "sh" (in directory "D:JenkinsJenkins_homeworkspacejmeter_test"): CreateProcess error=2, 系统找不到指定的文件。
    使用jmeter使用Jenkins发送自定义消息内容
  • 原文地址:https://www.cnblogs.com/i201102053/p/10304570.html
Copyright © 2011-2022 走看看