Python -- 文件操作、异常及模块知识总结

本文详细介绍了Python的文件操作,包括文件的写入(创建)、读取、备份(复制)以及非文本文件的复制。同时,讲解了异常处理的基本语法,如try-except-finally结构。此外,还涵盖了模块的导入方式以及如何调用模块中的函数和包的使用。
摘要由CSDN通过智能技术生成

目录

一、文件操作

1. 文件写入(文件不存在会自动创建)

2. 文件读取

3. 文件备份(复制)

4. 非文本文件的复制

二、异常

三、模块

1. 导入模块的方式

2. 调用模块中的函数

3. 包相关

总结


一、文件操作

1. 文件写入(文件不存在会自动创建)

# 1.open() 打开通道
    file_io = open(r"C:\Users\Administrator\Desktop\WeChat.txt","w",encoding='utf-8')  # r表示免转译(\)    w代表write(覆盖写入)
    file_io = open(r"C:\Users\Administrator\Desktop\WeChat.txt","a",encoding='utf-8')    # r表示免转译(\)    a表示追加写入
    # "w"或"a"模式无文件会自动创建文件,  "r"模式会报错.

# 2.读写数据
file_io.write('Alfie1')

# 3.刷新缓冲区  数据量大的时候需要操作
file_io.flush()

# 4.关闭通道  可以再释放资源前刷新一次缓冲区
file_io.close()

2. 文件读取

# 1. open() 打开通道
	file_io = open(r"C:\Users\Administrator\Desktop\WeChat.txt","r",encoding='utf-8') # r表示免转译(\)

# 2.读取数据
	读取全部数据  all_str = file_io.read()     # 一次性读取完毕, 但是如果数据量太大,会内存溢出.
	按照指定的字节读取    data = file_io.read(10)
	一次性读取所有的行    all_line = file_io.readlines()
	一次读取一行
	while True:
        line = file_io.readline()
        if len(line) <= 0:
            break
        # if not line:  # 只有为空字符才会转换为False.
# 3.打印数据
# 4.关闭通道
	file_io.close()
	注意    filepath: 表示文件所在的路径(相对路径和绝对路径都可以.)

3. 文件备份(复制)

# 小文件
	# 源文件   :  C:\Users\Administrator\Desktop\WeChat.txt
    # 目标文件 :  项目下的 a.txt

     file_in  = open(r"C:\Users\Administrator\Desktop\WeChat.txt","r",encoding='utf-8')
     file_out = open("a.txt","w",encoding='utf-8')

    # 读取源文件的数据
     data = file_in.read()

    # 写入目标文件
     file_out.write(data)

    # 关闭通道
     file_in.close()
     file_out.close()

# 大文件
	# 如果是大文件,复制需要一行一行来,防止内存溢出.
     file_in  = open(r"C:\Users\Administrator\Desktop\WeChat.txt","r",encoding='utf-8')
     file_out = open("a.txt","w",encoding='utf-8')

    # 读取源文件数据
     count = 0
     while True:
         line = file_in.readline()
         if line: # 如果有数据,就写入目标文件.
             file_out.write(line)
             count += 1
             if count % 10000 == 0:  # 万次写入,刷新一次缓冲区,减少对硬盘和内存的交互,减少其伤害.
                 file_out.flush()
         else:
             print("文件复制完毕...")
             break

    # 关闭通道
     file_in.close()
     file_out.close()

4. 非文本文件的复制

# 源文件通道:
file_in = open(r"E:\Wallpaper\1.jpg","rb")

# 目标文件通道:
file_out = open(r"E:\Wallpaper\2.jpg","wb")

# 从源文件通道读,写出到目标文件中.
count = 0
while True:
    data = file_in.read(1024)
    file_out.write(data)
    count += 1
    if count % 1000 == 0:
        file_out.flush()
    if len(data) == 0:
        break

# 关闭通道,释放资源.
file_in.close()
file_out.close()

二、异常

# 捕捉指定异常
    try:
    可能发生错误的代码
    except 异常类型:
        如果捕获到该异常类型执行的代码

# 异常的else
	try:
        print(1)
    except Exception as result:
        print(result)
    else:
        print('我是else,是没有异常的时候执行的代码')

# 异常的finally
	try:
        f = open('test.txt', 'r')
    except Exception as result:
        f = open('test.txt', 'w')
    else:
        print('没有异常,真开心')
    finally:
        f.close()

# 捕获所有异常
	try:
        print(num)
    except Exception as result:   # Exception是所有程序异常类的父类。
        print(result)

# 捕捉异常完整格式
	try:
      可能发生异常的代码
    except:
      如果出现异常执行的代码
    else:
      没有异常执行的代码
    finally:
      无论是否异常都要执行的代码

# 异常的传递方式    异常会传递给调用者  向上传递

三、模块

1. 导入模块的方式

导入模块的方式
	import 模块名
	    import random
        random.randint(1,3)

	from 模块名 import 功能名
		from random import randint
        randint(4,6)

	from 模块名 import *
		from random import *
    print(randint(7,9))

	import 模块名 as 别名
		import time as tt
        tt.sleep(2)
        print('hello')

	from 模块名 import 功能名 as 别名
		from time import sleep as sl
        sl(2)
        print('hello')

2. 调用模块中的函数

调用模块中的函数
	my_random
	# __all__ 表示要暴露的工具名,外界使用import * 导入,无法使用未暴露的工具.
    __all__ = ['randint']

    def randint():
        return 100

    def aaa():
        print("my_random-aaa")

    # python内置变量
    # print(__name__)  右键运行结果: __main__  导入运行结果: my_random
    if __name__ == '__main__':     # 作用: 屏蔽因调用模块多一次运行的结果.
        print(randint())                   # 只有右键运行才会等于main
	    调用动作
		from Py_Abnormal_Module.my_random import *
        print(randint())

    # aaa() 工具隐藏了
    from Py_Abnormal_Module.my_random import aaa
    aaa()

3. 包相关

包相关
	新建包(Python Package)
	在包里新建模块 -- my_module1 和 my_module2
	
    导入包
	import Py_Abnormal_Module.My_package.my_module1
    Py_Abnormal_Module.My_package.my_module1.info_print1()
	
    体验使用
	from Py_Abnormal_Module.My_package import *
    Py_Abnormal_Module.My_package.my_module1.info_print1()

总结

以上就是今天的内容,本文介绍了Python的文件操作,异常及模块相关问题.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值