Python开发3(控制语句和文件操作)

文章目录
  1. 1. python的控制语句
    1. 1.1. 循环语句
  • Python文件的处理
    1. 1. 文件的基本操作
      1. 1.1. 文件的打开和创建
      2. 1.2. 文件的写入
      3. 1.3. 文件的删除
      4. 1.4. 文件的删除
      5. 1.5. 文件的复制
      6. 1.6. 文件重命名
      7. 1.7. 文件内容的查找和替换
      8. 1.8. 文件的比较
      9. 1.9. 配置文件的访问
    2. 2. 目录的基本操作
      1. 2.1. 目录的创建和删除
      2. 2.2. 目录的遍历
    3. 3. 文件和流
      1. 3.1. Python的流对象
      2. 3.2. stdout是流的标准输出,前面的程序都是把程序的结果输出到控制台,现在通过stdout重定向输出,把输出结果保存在文件中。
      3. 3.3. stderr 错误输出
  • python的控制语句
    1
    2
    3
    4
    5
    6
    7
    x = input("x:")
    # input支持用户输入数字和表达式,最后返回数字类型,表达式会自动计算
    print(x)
    x = raw_imput("x:")
    # raw_input捕获原始输入,返回的是字符串类型
    x = int(x) # 如果需要使用数字类型,转换位数字类型
    x = x+1

    ####### switch语句

    switch语句容易造成代码不易维护,使源文件拥挤。面向对象程序设计,常常对switch语句进行重构,把switch语句分解成若干个类。当然对于分支流程简单的switch可以使用字典来实现,使用字典更加容易管理switch.
    字典是键值对组成的集合,类似JAVA的HashTable

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    # 使用字典实现switch
    from __future__ import division
    # python提供了__future__模块,把新版本的特性导入到当前版本
    x =1
    y = 2
    operator = "/"
    result = {
    "+": x+y,
    "*": x*y,
    "-": x-y,
    "/": x/y,
    }
    print result.get(operator)
    循环语句

    python循环语句包括while和for

    1
    2
    3
    4
    5
    6
    7
    ####### while循环
    numbers = raw_input("输入几个数字,以逗号分隔").split(",")
    # 输入数字,赋值给numbers列表
    x = 0
    if x < len(numbers):
    print numbers[x]
    x+1 = x

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    # 带else的while的循环语句
    x = input("输入x的值")
    i = 0
    while(x!=0):
    if(x>0)
    x-1=x
    else:
    x+1=x
    i+1=i
    print("第%d循环"%i, x)
    else:
    print("x等于0",x)

    ####### for循环
    for循环用于遍历一个集合,依次访问集合中的每一个项目

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    for 变量 in 集合:
    ...
    else:
    ...
    # 集合可以是元组、列表、字典等数据结构
    # 每次从集合中取出一个值并赋值给变量,else可以省略
    '''
    for循环通常与range()函数一起使用,range(开始,结束值,步长)返回一个列表
    range(5,-1,-1) ->[5,4,3,2,1,0] 包前不包后
    '''

    # for in 语句
    for x in range(-1,3,1):
    if x > 0 :
    print("正数",x)
    elif x == 0 :
    print("零",x)
    else:
    print("负数")
    else:
    print("函数结束")

    python中没有for(x=2;x<15;x++)这种表达式,可以使用:
    x= 0 while x < 5: print x x + 1=x

    ####### break 和 continue
    break: 直接中断循环
    continue: 停止本次循环,进入下一次循环

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    x = 4
    for y in range(0,20,):
    if x != y:
    print(y)
    continue
    else:
    print(x)
    break
    # x不等于y,continue,进入下次循环
    # x等于y,break中断循环,输入:0,1,2,3,4

    介绍下xrange()函数:
    xrange是一个类,返回一个xrange对象,`xrange(开始,结束值,步长)
    xrange()进行遍历的时候 每次只返回一个值
    range()返回的是列表
    一次性计算并返回所有的值**,

    1
    2
    3
    4
    5
    # xrange()
    x = xrange(0,8)
    print x #输出xrange(8),这是一个xrange对象
    print x[0] #输出 0
    print x[7] #输出最后一个元素的值 输出结果为:7

    ####### xrange()实现的冒泡排序算法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    def bubbleSort(numbers):
    for j in range(len(numbers)-1,-1,-1):
    for i in range(j):
    if numbers[i] > numbers[i+1]: # 把数值小的放到顶端
    numbers[i], numbers[i+1] = numbers[i+1], numbers[i]
    print(numbers)
    def main():
    numbers = [23,12,9,15,6]
    bubbleSort(numbers)
    if __name__ == '__main__':
    main()

    Python文件的处理

    数据的存储可以使用数据库(保持了数据完整性、关联性,数据更加安全可靠)和文件(简单易用,通常用于存储应用程序软件的参数和临时数据)

    文件的基本操作

    python提供os,os.path,shutil等模块用于处理文件用于处理文件,包括:
    文件的创建、读写、修改和复制、删除和重命名
    文件内容的搜索和替换
    文件内容的比较
    配置文集的读写,目录创建和遍历
    文件和流

    文件的打开和创建

    python使用内联函数file()创建和打开文件, 返回一个file对象可以对文件进行各种操作
    使用open()可以替换file(),open()是file()的别名

    1
    2
    file(name, mode, buffering)
    # name:被打开文件的名称,mode文件的打开模式,buffering设置缓存模式,0是无缓存,1表示行缓存,>1表示缓冲区的大小以字节为单位

    模式名称 含义
    r 以只读方式打开
    r+ 以读写方式打开
    w 以写入方式打开,先删除原有内容,再写入新的数据,如果文件不存在就创建一个新的文件
    w+ 以读写方式打开,先删除原有内容,再写入新的数据,如果文件不存在就创建一个新的文件
    a 以写入方式打开,在文件末尾增加新的内容,如果文件不存在就创建一个新的文件
    a+ 以读写方式打开,在文件末尾增加新的内容,如果文件不存在就创建一个新的文件
    b 以二进制方式打开文件,与r r+ w w+ a +结合使用
    U 支持所有换行符,\r \n \r\n

    对于图片,视频文件必须使用“b”(也就是二进制的方式读写)

    file的常用属性和方法:

    属性名称 方法
    Closed 判断文件是否关闭,关闭返回True
    Mode 显示文件的打开模式
    Encoding 显示文件的编码模式 print(f.Encoding) f是file对象
    Newlines 显示文件的换行模式
    file(name,mode,buffering) 以mode模式打开name文件
    flush 把缓存区内容写入磁盘
    close 关闭文件
    read(5) 读取文件中读取5个字节的内容作为字符串返回
    readline() 读取1行作为字符串返回,readlines(2)表示每行每次读取两个字节,直到行的末尾
    readlines() 读取每行的内容存储在列表中返回
    seek(offset, whence) 把文件指针移动到1个新的位置,offset是相对于whence的位置,whence为0从文件开始的位置计算,为1表示从当前位置计算,为2表示从文件末尾位置计算
    tell() 返回文件指针的位置
    next() 返回下一行的内容,并将文件的指针移动到下一行
    truncate(size) 删除size个字节的内容
    write(str) 将字符串str的内容写入文件
    writelines(str) 将字符串序列的内容写入文件
    1
    2
    3
    4
    5
    6
    7
    # 文件的创建
    content = '''hello world
    hello myladys '''

    f = open('hello.txt','w')
    f.write(content)
    f.close()
    # 这里是有三引号 可以输出换行,三引号用来输出换行、单引号、双引号

    ####### 文件的读取
    1.readline() 每次只读取文件中的一行,需要使用永真表达式循环读取,知道文件的指针移动到文件末尾,再使用readlines()错误,使用break中断循环

    1
    2
    3
    4
    5
    6
    7
    8
    9
    # 使用readlines读取文件
    f = open('hello.txt','r')
    while True:
    line = f.readline()
    if line:
    print(line)
    else:
    break
    f.close

    2.多行读取readlines()

    1
    2
    3
    4
    5
    # 使用readlines读取文件
    f = open('hello.txt','r')
    lines = f.readlines()
    for line in lines:
    print(line)

    3.一次性读取read()
    读取文件最简单方法是read(),read()读出文件的所有内容并赋值给一个字符串变量

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    # 使用read读取文件
    '''
    f = open('hello.txt','r')
    str = f.read()
    print(str)
    '''

    # 通过控制read的参数,并返回指定字节的内容
    f = open('hello.txt','r')
    content = f.read(5) #读取5个字节作为字符串
    print(content)
    print(f.tell())
    content_next = f.read(5) #从上次读取结束后的指针位置开始读取5个字节返回
    print(content_next)
    print(f.tell())
    f.close()

    文件的写入

    write()把字符串写入文件,writelines()方法把列表中存储的字符串写入文件。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    f = open('hello.txt','w+')
    f.writelines(["hi,mylady\n","yes,myload"])
    # f.write('''hi,mylady,
    yes,myload
    ''')
    f.close()
    # 追加新的内容
    f = open('hello.txt','a+')
    content = "I have waited for the days for a long time"
    f.write(content)
    f.close()

    文件的删除

    文件的删除需要使用os,os.path模块,os模块提供了对系统环境、文件、目录等操作系统级的接口函数
    markdown全角模式下ctrl+space在点击space就输入了空格

                  os模块的常见文件处理模块

    函数 说明
    access(path,mode) 按照mode指定权限访问文件
    open(filename,flag,mode=0777) 按照mode指定权限打开文件,默认给所有用户读写,执行权限
    change(path,mode) 改变文件的访问权限,mode需要使用Unix系统的权限代号表示
    remove(path) 删除path指定的文件
    rename(old,new) 重命名文件或者目录,old是原文件或目录
    stat(path) 返回path指定文件的所有属性
    fstat(path) 返回打开文件的所有属性
    lseek(fd,pos,how) 设置文件当前位置,返回当前位置的字节数
    tmpfile() 创建一个临时文件,文件创建在操作系统的临时目录中

    os模块的open()函数与内联的file(),open()函数用法不同

                os.path模块的常用函数

    函数 说明
    abspath(path) 返回path所在的绝对路径
    dirname(p) 返回目录路径
    exists(path) 判断文件是否存在
    getatime(filename) 返回文件的最后访问时间
    getctime(filename) 返回文件的创建时间
    getmtime(filename) 返回文件的最后修改时间
    getsize 返回文件的大小
    isabs(s) 返回路径是否为绝对路径
    isdir(path) 判断path指定的是否为目录
    isfile(path) 判断path指定的是否为文件
    split(p) 对路径进行分割,并以列表形式返回
    splittext(p) 在路径中分割文件的扩展名
    Splitdriver(p) 从路径中分割驱动器的名称
    walk(top,func,org) 遍历目录数, 与os.walk()功能相同
    文件的删除
    1
    2
    3
    4
    5
    6
    7
    import os
    if os.path.exists('hello.txt'): #调用os.path模块的exist方法判断文件hello.txt是否存在
    os.remove("hello.txt") #调用remove()方法删除hello.txt
    # 删除桌面上的文件
    import os
    if os.path.exists('C:/Users/LW/Desktop/hello.txt'):
    os.remove("C:/Users/LW/Desktop/hello.txt")
    文件的复制

    file类没有提供复制文件的方法,但可以利用read(),write()方法模拟实现文件复制

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # 利用read()、write()方法实现复制
    file1 = open('hello.txt','w')
    content1= ["hi,mylady\n","yes,myload\n"]
    file1.writelines(content1)
    file1.close()
    # 把hello1.txt的内容复制到hello2.txt的内容
    file1_read = open('hello.txt','r')
    file2 = open('mylady.txt','w')
    file2.write(file1_read.read())
    file1_read.close()
    file2.close()

    shutil模块是一个文件、目录的管理接口,提供一些用于文件、目录复制的函数:

    1
    2
    3
    4
    5
    6
    7
    8
    import shutil
    copefile(src, dst) #copefiel()函数用于文件的拷贝
    # src表示源文件的路径,dst表示目标文件的路径,
    move(src, dst)
    # 移动一个目录或文件到指定的位置,可以根据参数dst重新命名移动后的文件
    import shutil
    shutil.copyfile('mylady.txt','myload.txt')
    shutil.move('mylady.txt','../becase.txt')
    文件重命名

    利用os.rename(可以对文件或目录进行重命名

    1
    2
    3
    4
    5
    import os
    filelist = os.listdir(".") #.表示当前目录,listdir返回当前目录的文件列表[]
    print(filelist)
    if "myload.txt" in filelist:
    os.rename("myload.txt", "mylady.txt")

    更改后缀名:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    # 修改txt后缀名为md
    import os
    filelist = os.listdir(".")
    print(filelist)
    for file in filelist:
    spilt_point = file.find(".")
    if file[spilt_point+1:] == "txt": #列表分片,又忘了,头大
    new_name = file[:spilt_point+1]+"md"
    os.rename(file,new_name)
    '''
    为了获取文件的后缀名,先找到“.”的位置,再通过分片file[split_point+1:]截取后缀名
    也可以使用 os.path模块的函数splitext()来实现,splitext()返回一个列表,第一个部分是文件名,
    第二个部分是后缀名
    '''

    # 修改txt后缀名为md
    import os
    filelist = os.listdir(".")
    for file in filelist:
    namelist = os.path.splitext(file)
    if namelist[1] == ".md":
    new_name = namelist[0] + ".txt"
    os.rename(file,new_name)

    glob模块用于路径的匹配,返回给定匹配条件的文件列表。glob模块组重要的函数就是glob(),该函数返回符合同一匹配条件的多个文件
    golb()函数的参数应该符合正则表达式的语法要求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    # 返回后缀为html的文件列表
    import glob
    list = glob.glob("*.txt")
    print(type(list))
    print(list)
    '''
    glob做更多的匹配匹配出桌面的内容
    '''

    import glob
    # list = glob.glob("C:/Users/LW/Desktop/b*.txt") #以b开头的txt文件
    list =glob.glob("C:/Users/LW/Desktop/p*/*.py") #输出桌面p开头文件夹中的python文件
    # 注意使用正则表达式
    print(list)
    文件内容的查找和替换
    1
    2
    3
    4
    5
    6
    7
    8
    9
    import re
    f = open("hello.txt","r") #得到文件对象f
    count = 0
    for single_line in f.readlines(): #每次读取一行保存到变量single_line
    list = re.findall("hello",single_line) #调用re模块findall(),讲查找的结果保存在列表list中
    if len(list) > 0:
    count = count + list.count("hello") #调用列表的count()方法,统计当前列表的list个数
    print("hello的个数是",count)
    f.close()

    文件内容的替换

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    # 把hello.txt的hello全部替换成hi,并把结果保存到文件hello2.txt
    f1 = open('hello.txt','r')
    f2 = open('hello2.txt','w')
    for s in f1.readlines():
    f2.write(s.replace("hello","hi"))
    f1.close()
    f2.close()
    '''
    把f1中内容替换 为什么不行 后序
    f1 = open('hello.txt','r+')
    for s in f1.readlines():
    s.replace("hello","hi")
    f1.close()
    单个文件的执行为什么不行
    '''

    文件的比较

    python使用difflib模块实现对序列、文件的比较。如果需要列出两个文件的不同,使用difflib模块的SequenceMatcher类来实现,其中get_opcodes()可以返回两个序列的比较结果,是一个元组

    在调用get_opcodes()方法之前,需要生成一个SequenceMatcher对象
    SequenceMatche(匹配指定的字符或字符串,待比较序列a,待比较序列b)
    a,b序列谁在前谁是标准

    1
    费事,我还是使用git diff吧
    配置文件的访问

    应用程序中,通常使用配置文件定义一些参数。例如:数据库的配置文件用于记录数据库的字符串连接、主机名、用户名、密码等,Windows的ini是一种传统的配置文件,ini由多个块组成,每个块有多个多个配置项。例如ODBC.ini记录了windows下各种数据库系统的ODBC驱动信息。
    1.读取配置文件的内容
    Python的标准库ConfigParser模块用于解析配置文件,



    目录的基本操作
    目录的创建和删除
    函数 说明
    mkdir(path) 创建path指定的目录
    makedirs(path) 创建doc/hello形式的多级目录
    rmdir(path) 删除path指定的目录
    removedirs(path) 删除path指定的多级目录
    listdir(path) 返回path下所有的文件
    getcwd() 返回当前的工作目录
    chdir(path) 将当前目录改为path指定的目录
    walk(top,topdown=True,onerror= None) 遍历目录树
    1
    2
    3
    4
    5
    import os
    os.mkdir("hello")
    os.makedirs("may/day") # 创建多级目录
    os.rmdir("hello")
    os.removedirs("may/day") # 删除多级目录


    目录的遍历

    目录的遍历有三种方式:
    递归函数、os.path.walk(), os.walk()
    1.递归函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import os
    def VisitDir(path):
    list = os.listdir(path)
    for each_path in list:
    pathname = os.path.join(path,each_path)
    #调用os.path模块的join函数,获取文件的完整路径保存到pathname变量中
    if not os.path.isfile(pathname):
    VisitDir(pathname)
    # 判断pathname是否为目录,如果为目录则递归调用VisitDir(path)继续遍历底层目录
    else:
    print(pathname)
    if __name__ == '__main__':
    path = r"C:\Users\LW\Desktop\python笔记" #r""可以处理特殊字符串比如路径
    # path = "C:/Users/LW/Desktop/python笔记" #linux中的/写法也可以,推荐上面
    VisitDir(path)



    2.C和C++中必须使用函数递归对目录进行遍历,python可以使用os.path模块的walk()函数进行遍历
    python3不支持,ca擦

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    # walk()函数简介
    walk(需要遍历的路径, 回调函数, 传递给回调函数的元组)
    回调函数:对遍历路径进行处理,回调函数就是作为一个函数的参数使用,触发某个事件则调用定义好的回调函数处理这个任务。
    回调函数的3个参数:1.walk()函数的元组,2.文件列表3.目录列表

    import os,os.path
    def VisitDir(arg,dirname,names):
    for filespath in name:
    print(os.path.join(dirname,filespath))

    if __name__=="__main__":
    path= r"C:\Users\LW\Desktop\python笔记"
    os.path.walk(path,VisitDir,())

    3.os.walk()也可用于python的遍历,os.walk()比os.path.walk()更加高效,而且不需要回调函数更加容易使用。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import os
    def VisitDir(path):
    for root,dirs,files in os.walk(path):
    for filepath in files:
    print(os.path.join(root,filepath))# 输出目录下遍历的文件
    '''
    for dirpath in dirs:
    print(os.path.join(root,dir)) #输出目录下遍历的文件夹
    '''


    if __name__ == '__main__':
    path = r"C:\Users\LW\Desktop\Mypython"
    VisitDir(path)



    os.walk()具体用法

    1
    2
    3
    4
    5
    >walk(path,topdown=True,onerror=None)
    >1.path表示遍历树的路径
    >2.topdown=True表示先返回根目录下文件,在遍历子目录的文件,False表示先遍历子目录的文件,再返回根目录下的文件
    >3.onerror=None 表示忽略文件遍历过程中产生的错误,否则提供一个自定义函数提示错误信息后继续遍历或者终止遍历
    >4.该函数返回一个元组,这三个参数分别是遍历路径名,目录列表,文件列表


    文件和流

    读写文件的方式有多种,如文件的读写,数据库的读写。为了有效的表示数据的读写,把文件、外设、网络连接等数据传输抽象成流。数据的传输好像流水从一个容器流到另一个容器。

    Python的流对象

    Python隐藏了流机制,在python的模块中找不到类似Stream的类。python把文件的处理和流关联在一起,流对象实现了File类的所有方法。
    sys提供了三种基本的流对象:
    stdin: 标准输入
    stdout: 标准输出
    stderr: 错误输出

    1
    2
    3
    4
    5
    6
    7
    # stdin是流的标准输入,可以通过stdin读取hello.txt的内容
    可以理解把文件的内容输入到流
    import sys

    sys.stdin = open("hello.txt","r")
    for file in sys.stdin.readlines():
    print(file)
    stdout是流的标准输出,前面的程序都是把程序的结果输出到控制台,现在通过stdout重定向输出,把输出结果保存在文件中。
    1
    2
    3
    4
    5
    6
    import sys

    sys.stdout = open(r"./hello.txt","r+")
    # 以追加模式打开当前目录下的文件hello.txt,并把hello.txt设置为终端输出设备(默认是系统的控制台)
    print("goodbye my almost lover")
    sys.stdout.close()
    stderr 错误输出

    日志文件通常会记录应用程序每次操作的执行结果。日志文件的记录便于维护人员了解当前系统的状况,甚至可以用于数据的回复(比如数据库的日志文件)。

    python的stderr用于记录、输出异常信息,通过stderr对象可以实现日志文件的功能。例如,当error_log.txt的内容为空,就在日志文件的error.log中记录异常的信息。如果error_log.txt的内容不为空,就在日志文件的error.log中记录正确的信息。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import sys,time

    sys.stderr = open("error.log","a")
    f = open("error_log.txt","r")
    t = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    content = f.read()
    if content:
    print("监控文件正常")
    sys.stderr.write(t+""+content)
    else:
    raise Exception(t + "异常信息")
    # 如果文件的内容不为空,则向error.log记录当前时间和txt内容
    # 文件为空抛出异常,在error.log记录当前时间和异常信息。



    (2) 模拟Java的输入、输出流(输入输出以文件为对象,FileInputStream文件输入流,把文件的内容写入流)
    先调用函数FileInputStream()读取该函数的参数hello.txt文件,然后调用函数FileOutputStream()吧FileInputStream()读取到的内容写入到hello2.txt文件中(相当于COPY文件的内容)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    # 文件输入流
    def FileInputStream(filename): #采用Generator函数的设计风格,模拟java的FileInputStream的工作方式
    try:
    f = open(filename,'r')
    for line in f: #控制读取文件每行的数据
    for byte in line: #控制读取每个字节的数据
    yield byte # yiel保留字返回每个字节的数据
    except StopIteration as e:
    f.close
    return
    # 文件输出流
    def FileOutputStream(inputStream,filename):
    try:
    f = open(filename,'w')
    while True:
    byte = inputStream.__next__() #获取取yield保留字产生的字节
    f.write(byte) # write可以把字符串和字节写入,writelines()把列表的内容写入
    except StopIteration as e:
    f.close()
    return

    if __name__ == '__main__':
    FileOutputStream(FileInputStream('hello.txt'),'mylady.txt')

    (3) 设计文件属性浏览程序(写轮子、用别人的好轮子、不要重复造轮子

    学习函数类、基本概念,是用来解决实际问题的

    程序需要解决的问题:通过给定目录路径查看文件的名称、大小、创建时间、最后修改日期和最后访问日期。
    ShowFileProperties()的实现大概分3个步骤。

    1. 遍历path指定的目录,获取每个子目录的路径
    2. 遍历子目录下的所有文件,并返回文件的属性列表
    3. 分解属性列表,将属性列表的值格式化输出

    使用glob模块查找文件

    1
    2
    3
    4
    import glob
    # list = glob.glob("C:/Users/LW/Desktop/b*.txt") #以b开头的txt文件
    list =glob.glob("C:/Users/LW/Desktop/p*/*.py")
    print(list)

    分享到 评论