Python文件IO与异常处理

Python文件IO与异常处理

  • 1、文件I/O
    • 1.1、文件访问
    • 1.2、文件写入
    • 1.3、文件读取
    • 1.4、文件关闭
    • 1.5、OS文件/目录方法
    • 1.6、With上下文管理
  • 2、Python异常处理
    • 2.1、异常捕获
    • 2.2、自定义异常
  • 3、常用文件IO操作
    • 3.1、递归遍历指定目录下的指定类型文件
    • 3.2、递归遍历指定目录下的指定类型文件或目录
    • 3.3、复制文件/目录到指定目录下
    • 3.4、文件/目录剪切
    • 3.5、文件压缩
    • 3.6、文件解压缩
    • 3.7、Excel-Sheet表转CSV
    • 3.8、将指定目录下的指定文件垂直合并
    • 3.9、提取文本文件中匹配正则的字符串列表
    • 3.10、词频统计
    • 3.11、TXT文本文件格式化
  • 4、StringIO与BytesIO
  • 5、异步IO(asyncio异步编程)
    • 5.1、基本概念
    • 5.2、应用案例



1、文件I/O

1.1、文件访问

'''
open('文件路径',mode='操作模式',encoding='编码方式')
常用操作模式有:
只读:r
只写:w
只追加:a
可读可追加:a+
读写:r+/w+
以二进制格式打开一个文件只读:rb
以二进制格式打开一个文件只写:wb
以二进制格式打开一个文件读写:rb+/wb+
'''
# Python内置的open()函数用于打开一个文件(创建文件),创建一个file对象
file = open("foo.txt", 'r+')
file = open("foo.txt", 'w')

# file对象的属性
print("文件名:"+file.name)
print("文件是否已关闭:"+file.closed)
print("文件访问模式:"+file.mode)

1.2、文件写入

file.write("www.site.com!\nVery good site!\n")
file.flush()

1.3、文件读取

# file.read([以字节计数,若未传入,则读取全部])
res = file.read()
print(res)

# 读取一行
line = file.readline()

# 读取所有行,返回列表
lines = file.readlines()

1.4、文件关闭

file.close()
del file       # 回收应用程序级的变量

1.5、OS文件/目录方法

重命名和删除文件,需要使用os模块

import os

os.rename("foo.txt", "new_foo.txt")
os.remove("new_foo.txt")

print(os.path.exists('path'))     # 文件是否存在
print(os.path.isdir('path'))      # 是否是文件夹/目录
print(os.path.isfile('path'))     # 是否是文件
print(os.path.abspath('path'))    # 返回绝对路径

os.mkdir('path')                  # 创建目录
os.makedirs('p1'/'p2'/'...')      # 创建多级目录
os.rmdir('path')                  # 删除目录(必须是空目录)
os.remove('path')                 # 删除文件
os.rename('src', 'dest')          # 重命名文件或目录

print(os.path.getsize('path'))    # 获取文件大小(字节)
print(os.listdir('path'))         # 获取指定目录下全部

其它os操作详见:传送门

shutil和glob文件操作见本文第3节

1.6、With上下文管理

with open() as写法:with会自动执行file.close()

"""
with open('path', 'mode', encoding='utf-8') as file:
    contents = file.read()        # 读取
    print(contents)
    file.write(contents)          # 写入
"""

2、Python异常处理

异常处理:当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行

2.1、异常捕获

# 1)try...except...else语句
'''
try:
   语句
except 异常名:
   try中发生异常进行处理
else:
   没有异常发生时执行的代码
'''
try:
    fh = open("textfile.txt", "w")
    fh.write("测试异常")
except IOError:
    print("没有找到文件或读取文件失败")
else:
    print("文件写入成功")
    fh.close()
# 2)try...except...finally语句:无论是否发生异常都将执行finally代码

try:
    fh = open("textfile.txt", "w")
    fh.write("测试异常")
except IOError:
    print("没有找到文件或读取文件失败")
finally:
    fh.close()

2.2、自定义异常

1) 自定义异常:自定义异常类继承基类Exception或子类RuntimeError等

class BaseError(Exception):
    # __init__构造方法用于接收一些参数来设置异常信息,例如错误码、错误消息等
    def __init__(self, code, msg):
        self.code = code
        self.msg = msg

    # 重写__str__方法用于返回异常的描述信息,相当于Java的toString()方法
    def __str__(self):
        return f"{
     self.code}: {
     self.msg}"

2) 案例1:手动触发异常

try:
    # raise语句用于手动触发异常;变量e用于创建类的实例
    raise BaseError(400, 'Raise is used to test Exception')
except BaseError as e:
    print(e)
'''
400: Raise is used to test Exception
'''

3) 案例2:主动抛出异常(主动抛出的异常同样也会导致程序的终止)

# if not x 用法:用于判断x是否等于None、False、""、0、空列表[]、空字典{}、空元祖()
ls_t = []
try:
    if not ls_t:
        raise Exception("The List is Empty.")
except Exception as e:
    print(e)
'''
The List is Empty.
'''

4) 使用traceback获取异常堆栈信息

import traceback

# print_exc()函数用于打印异常堆栈的详细信息
traceback.print_exc()
# format_exc()函数用于返回异常堆栈信息的字符串
print(traceback.format_exc())

3、常用文件IO操作

Python中的os和shutil是用于处理文件和目录操作的标准库

shutil库是os库的扩展,提供了更高级的文件和目录操作功能,如复制、移动、剪切、删除、压缩解压等

shutil模块对压缩包的处理是调用ZipFile和TarFile两个模块来进行的

常用方法有:

'''
1)复制
复制文件到目录:shutil.copy(src, dst)
复制文件内容到目标文件(dst不存在则创建,存在则覆盖):shutil.copyfile(src, dst)
复制文件夹:shutil.copytree(src, dst)
2)移动/剪切(可改名):shutil.move(src, dst)
3)删除
删除文件夹(文件夹必须为空):os.rmdir(dir)
递归删除文件夹:shutil.rmtree(dir)
4)压缩、解压
创建压缩文件(zip):zipfile.write(file)
读取压缩包文件:zipfile.namelist(path)
解压压缩包单个文件:zipfile.extract(file)
解压到当前目录:zipfile.extractall(path)
'''

准备:在桌面创建Test目录如下:

'''
Test/
    ├── Test1/     
    │        ├── d.txt
    │        └── e.xlsx
    ├── a.xlsx
    ├── b.txt
    └── c.xlsx
'''

3.1、递归遍历指定目录下的指定类型文件

import os

def get_files(path, suffix, recursion=False):
    try:
        # 判断目录是否存在
        if not os.path.exists(path) or os.path.isfile(path):
            raise IOError("目录不存在或不是目录!")
        # 获取所有文件及目录名(带后缀)
        list_file = os.listdir(path)
        # 拼接路径
        files = [os.path.join(path, file) for file in list_file]
        # 筛选指定文件
        res_files = [file for file in files if os.path.isfile(file) and file.endswith(suffix)]
        if recursion:
            # 筛选目录
            dirs = [dir for dir in files if os

你可能感兴趣的:(#,Python,#,数据分析,python,开发语言)