【Python快速入门和实践007】Python中的文件操作与异常处理

7. 文件操作与异常处理

   7.1 文件的读取与写入

     7.1.1 读写文本文件

读取文本文件:

  1. 打开文件:

    • 使用 open() 函数以 'r' 模式打开文件,这表示以只读模式打开文件。
    • 如果文件不存在,会抛出 FileNotFoundError
  2. 读取文件内容:

    • 使用 read() 方法读取整个文件的内容。
    • 使用 readline() 方法读取一行内容。
    • 使用 readlines() 方法读取所有行到列表中。
  3. 关闭文件:

    • 使用 close() 方法关闭文件,或者使用 with 语句自动管理文件的打开和关闭。

示例代码:

# 读取文本文件
filename = 'example.txt'

try:
    with open(filename, 'r') as file:
        # 读取整个文件
        content = file.read()
        print(content)
        
        # 逐行读取
        for line in file:
            print(line.strip())  # strip() 方法移除行尾的换行符
        
        # 读取所有行到列表
        lines = file.readlines()
        print(lines)
except FileNotFoundError:
    print(f"File '{filename}' not found.")

写入文本文件:

  1. 打开文件:

    • 使用 open() 函数以 'w' 模式打开文件,这表示以写入模式打开文件。如果文件已经存在,它会被覆盖。
  2. 写入数据:

    • 使用 write() 方法写入字符串。
    • 使用 writelines() 方法写入一个字符串列表。
  3. 关闭文件:

    • 使用 close() 方法关闭文件,或者使用 with 语句自动管理文件的打开和关闭。

示例代码:

# 写入文本文件
data_to_write = "Hello, world!\nThis is a test."

try:
    with open('output.txt', 'w') as file:
        file.write(data_to_write)
except IOError as e:
    print(f"An error occurred while writing to the file: {e}")

     7.1.2 读写二进制文件

读取二进制文件:

  1. 使用 open() 函数以 'rb' 模式打开文件。
  2. 使用 read() 方法读取二进制数据。

写入二进制文件:

  1. 使用 open() 函数以 'wb' 模式打开文件。
  2. 使用 write() 方法写入二进制数据。

示例代码:

# 读取二进制文件
with open('image.png', 'rb') as file:
    binary_data = file.read()

# 写入二进制文件
binary_data_to_write = b'\x00\x01\x02\x03\x04'
with open('binary_data.bin', 'wb') as file:
    file.write(binary_data_to_write)

   7.2 文件与目录操作

文件与目录的操作通常涉及创建、删除、重命名文件或目录等。可以使用 osos.path 模块来完成这些任务。

import os

# 创建目录
os.makedirs('new_directory/subdirectory')

# 删除目录
os.rmdir('new_directory/subdirectory')  # 目录必须为空
os.removedirs('new_directory/subdirectory')  # 递归删除空目录

# 重命名文件
os.rename('oldfile.txt', 'newfile.txt')

# 删除文件
os.remove('file_to_delete.txt')

# 列出当前目录下的所有文件和子目录
files = os.listdir('.')
for f in files:
    print(f)

# 获取当前工作目录
current_dir = os.getcwd()
print("Current directory:", current_dir)

# 改变当前工作目录
os.chdir('new_directory')

# 获取文件大小
size = os.path.getsize('example.txt')
print("File size:", size)

# 获取文件最后修改时间
mtime = os.path.getmtime('example.txt')
print("Last modified time:", mtime)

# 获取文件最后访问时间
atime = os.path.getatime('example.txt')
print("Last access time:", atime)

# 拼接路径
path = os.path.join('new_directory', 'subdirectory', 'file.txt')
print("Joined path:", path)

# 拆分路径
path_parts = os.path.split('/home/user/new_directory/subdirectory/file.txt')
print("Split path:", path_parts)

# 拆分路径和文件名
dir_name, file_name = os.path.split('/home/user/new_directory/subdirectory/file.txt')
print("Directory name:", dir_name)
print("File name:", file_name)

# 拆分文件名和扩展名
file_name, ext = os.path.splitext('file.txt')
print("File name:", file_name)
print("Extension:", ext)

# 检查路径是否存在
exists = os.path.exists('example.txt')
print("Exists:", exists)

# 检查是否为文件
is_file = os.path.isfile('example.txt')
print("Is file:", is_file)

# 检查是否为目录
is_dir = os.path.isdir('new_directory')
print("Is directory:", is_dir)

# 规范化路径
norm_path = os.path.normpath('/home/user/..')
print("Normalized path:", norm_path)

# 获取绝对路径
abs_path = os.path.abspath('example.txt')
print("Absolute path:", abs_path)

# 获取相对路径
rel_path = os.path.relpath('/home/user/new_directory/subdirectory', '/home/user/new_directory')
print("Relative path:", rel_path)

# 获取环境变量
env_var = os.environ.get('HOME')
print("Home directory:", env_var)

# 设置环境变量
os.environ['TEST_VAR'] = 'test_value'

# 调用外部命令
output = os.system('ls -l')
print("Command output:", output)

   7.3 异常处理

        在 Python 中,异常处理是一种控制程序流的方式,它允许程序在遇到错误时能够继续执行或优雅地退出,而不是直接崩溃。

     7.3.1 try-except 结构

        try-except 结构允许你在尝试执行某段代码时捕获并处理可能出现的异常。这样即使出现错误,程序也不会突然终止,而是可以继续执行。

示例代码:

# example_exception_handling.py
try:
    with open('nonexistent_file.txt', 'r') as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("File not found.")

# 结果
File not found.

     7.3.2 异常类型与处理

        Python 提供了许多内置异常类型,例如 FileNotFoundErrorValueError 等。你可以根据需要捕获特定类型的异常。

示例代码:

# example_exception_types.py
try:
    with open('example.txt', 'r') as file:
        content = int(file.read())
except ValueError:
    print("Could not convert data to an integer.")
except FileNotFoundError:
    print("The file does not exist.")

# 结果
Could not convert data to an integer.

     7.3.3 finally 语句

        finally 子句无论是否发生异常都会被执行。这通常用于清理工作,例如关闭文件等。

示例代码:

# example_finally.py
try:
    with open('example.txt', 'r') as file:
        content = file.read()
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    print("This will always be executed.")

# 结果
An error occurred: [Errno 2] No such file or directory: 'example.txt'
This will always be executed.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值