Python编程学习-基础笔记05

七、文件操作

7.1 系统函数open

参数:file,mode,buffering,encoding

mode:

​ 纯文本:r:read,:write

​ a: 追加,打开文件并将内容追加到后面

​ b:binary 二进制流,图片,音乐,电影等

​ rb:read binary, wb: write binary

读或写都是相对于pycharm而言的,从文件输入到pycharm就是读操作,从pycharm输出到文件就是写操作。

'''
文件操作:
    文件上传
    保存log
系统函数:
    open(file,mode,buffering,encoding)
    读:
        open(path/filename,'rt') --> 默认mode是rt,返回值:stream,类似管道
        container = stream.read() --> 读取管道中的内容
        注意:如果路劲或文件有误,报错FileNotFoundError,文件类型有误,
        读取图片,不能使用默认读取方式, 应mode = 'rb'
        read(), 一次读取所有
        readable() 判断文件是否可读
        readline() 一次读取一行
        readlines() 一次读取所有行保存到列表
    写:
        open(path/filename,'w')
        write(内容),每次都会覆盖之前的
        writelines(iterable) 写多行内容,但是没有换行的效果
        open(path/filename,'a')
        write(内容),将内容加到文件最后,不会覆盖原来内容
'''
#读
stream = open('a.txt')
result = stream.readable() #判断文件是否可读 True False
print(result) #True
# container = stream.read() #读取管道中的内容

# line = stream.readline() #读取一行
# print(line) #hello world

line = stream.readlines() #读取多行,存入到列表
print(line) #['hello world\n', 'You are awesome']
for line in stream.readlines():
    print(line)

stream.close()
#写
stream = open('a.txt','a')
s = '''
hello,
    welcome to my blog!
    we can stay together!
            Friends.
'''
stream.write(s)
stream.writelines(['小龙女\n','你在古墓可冷吗'])
stream.close()

7.2 复制文件

7.2.1 复制单个文件

# 复制单个文件
with open(r'./girl.jpg','rb') as stream:
    container = stream.read() #读取图片内容
    with open(r'./p1/girl.jpg', 'wb') as w_stream:
        w_stream.write(container) #写入图片内容
print('复制图片完成')

7.2.2 引入OS模块

'''
    1,引入os模块
        os.path.dirname(__file__) #获取当前文件所在目录
        os.path.join(path,'girl1.jpg') 返回拼接后的新路劲
        os.path.split(file)[1] 将其按文件和文件夹分隔,切割为一个元组2个元素,下标1为文件名
        os.path.splitext(file)[1]  分隔文件与扩展名
        os.path.exists()  查看文件夹是否存在
        os.mkdir('./test') 创建文件夹
        os.chdir('./test') 切换目录
        os.remove() 删除文件
        os.rmdir() 删除目录
'''
import os,time
# path = os.path.dirname(__file__) #获取当前文件所在目录
# print(path)
# path1 = os.path.join(path,'girl1.jpg') #返回拼接后的新路劲
r = os.path.isabs(r'./p1/girl.jpg') #判断路劲是否是决定路劲
print('------>',r)  #------> False
path = os.path.abspath(r'./p1/girl.jpg') #通过相对路劲获取绝对路劲
print(path)
path = os.getcwd() #获取当前文件的工作目录
print(path)
file = open(r'./p1/girl.jpg','rb').name
filename1 = os.path.split(file)[1]  # 将其按文件和文件夹分隔,切割为一个元组2个元素,下标1为文件名
print(filename1)  # 按元组下标取值
extend_name = os.path.splitext(file)[1]  # 分隔文件与扩展名
print(extend_name)  # .jpg
path = os.path.dirname(__file__)
with open(r'./p1/girl.jpg','rb') as stream:
    container = stream.read() #读取图片内容
    file = stream.name #读取文件全名
    print(file)
    filename = file[file.rfind('/')+1:] # 将最后的文件名切取出来,rfind得到的是字符串下标,从下标+1取到最后
    print(filename)

    path1 = os.path.join(path,filename) # 一次逗号多一层路劲
    with open(r'./p1/girl.jpg', 'wb') as w_stream:
        w_stream.write(container) #写入图片内容
#创建or 删除 文件夹
#判断目录不存在才可以创建目录
if not os.path.exists('./test'):
    os.mkdir('./test')
    f = open('./test/a.txt','w')
    f.write('test file')
    f.close()
#目录中没有文件才能用这种方式删除
# os.rmdir('./test')

#目录中有文件,首先需要删除文件然后删除目录
# os.remove('./test/a.txt')
path = './test'
filelist = os.listdir(path)
for file in filelist:
    #将文件拼接到路劲之后
    path1 = os.path.join(path,file)
    os.remove(path1)
else:
    os.removedirs(path)

7.2.3 批量复制文件或文件夹

import os
#文件复制
src_path = r'./p1'
target_path = r'./p2'
#封装成函数
def copy(src,target):
    #判断源和目标是否都是文件夹
    if os.path.isdir(src) and os.path.isdir(target):
        #列出文件夹中的文件或子文件夹,以列表形式出现
        file_list = os.listdir(src)
        #循环列表
        for file in file_list:
            #将文件和其目录拼接为新的路劲,便于复制
            path = os.path.join(src,file)
            # 将要复制的文件拼接到目标路劲
            path1 = os.path.join(target,file)
            #判断列表中的是否是文件夹
            if os.path.isdir(path):
                #判断目标中是否存在相同文件夹,不存在就创建,存在则直接复制
                if not os.path.exists(path1):
                    #是文件夹,去目标地创建一样的文件夹
                    os.mkdir(path1)
                #递归调用copy函数,每遇到一个文件夹调用一次
                copy(path,path1)
            #如果不是文件夹,直接开始复制文件
            else:
                #以rb模式打开源文件,可适应所有文件格式,默认的r只能读取文本
                with open(path,'rb') as rstream:
                    #将源文件读取到容器
                    container = rstream.read()
                # 以wb模式将源文件复制到目标地址
                with open(path1,'wb') as wstream:
                    #写入读取的内容
                    wstream.write(container)
        #循环完成之后,打印提示
        else:
            print('复制完毕')

#调用函数
copy(src_path,target_path)

7.3 异常处理

7.3.1 系统执行检测异常

'''
语法错误或异常:
语法错误:
    通常可以在pycharm程序编写过程中发现
异常:
    运行时才抛出异常错误
异常处理:格式
    try:
        pass #可能出现异常的代码
    except:
        pass #如果有异常,执行的代码
    finally:
        pass #无论是否存在异常都会执行的代码,optional
情况1:
    try:
        有可能产生多种异常
    except 异常类型1:
        print('提示异常类型1')
    except 异常类型2:
        print('提示异常类型2')
    except Exception:
        print('出错了!!',)
如果时多个except,异常类型的顺序要注意,最大的Exception要放到最后,不然就会到Exception而不往下进行
情况2:获取exception的错误原因
    try:
        有可能产生多种异常
    except 异常类型1:
        print('提示异常类型1')
    except 异常类型2:
        print('提示异常类型2')
    except Exception as err:
        print(err) --》err 就是错误原因
情况3:
    try:
        有可能产生多种异常
    except Exception as err:
        print(err) --》err 就是错误原因
    else:
        pass --> 没有异常才会去执行的代码

情况4:
    try:
        有可能产生多种异常
    except Exception as err:
        print(err) --》err 就是错误原因
    finally:
        pass --> 有没有异常都会去执行的代码
注意:如果都带return 返回值,只有finally中的往外返,其余的不会

'''

def func():
    try:
        a = int(input('请输入第一个数字:'))
        b = int(input('请输入第二个数字:'))
        opr = input('请输入运算符 + - * /:')
        result = 0
        if opr == '+':
            result = a + b
        elif opr == '-':
            result = a - b
        elif opr == '*':
            result = a * b
        elif opr == '/':
            result = a / b
        else:
            print('运算符输入错误!!')
        print(result)
    #根据异常类型来提示
    except ZeroDivisionError:
        print('除数不能为0!!')
    except ValueError:
        print('只能输入数字!!')
    except Exception as err:
        print('出错了!!',err)

#调用函数
func()

情况4

def register():
    username = input('请输入用户名:')
    if len(username) < 6:
        #往外抛异常
        raise Exception('用户名必须大于等于6位')
    else:
        print('输入的用户名是:',username)
def func():
    try:
        register()
        return 1
    except Exception as err:
        print(err)
        print('注册失败!')
        return 2
    finally:
        print('注册结束!')
        #只会返回这个return值
        return 3
#调用
r = func()
print(r)

7.3.2 程序主动抛异常

def register():
    username = input('请输入用户名:')
    if len(username) < 6:
        #往外抛异常
        raise Exception('用户名必须大于等于6位')
    else:
        print('输入的用户名是:',username)

try:
    register()
except Exception as err:
    print(err)
    print('注册失败!')
else:
    print('注册成功!')
posted @ 2022-07-04 10:26  逆流的鱼2016  阅读(26)  评论(0编辑  收藏  举报