6.6 目录操作

os模块简介

os模块提供了与操作系统交互的功能,包括文件和目录操作。

import os

print("当前Python版本的os模块功能演示")
print(f"操作系统类型: {os.name}")
print(f"当前工作目录: {os.getcwd()}")

输出结果:

当前Python版本的os模块功能演示
操作系统类型: nt
当前工作目录: C:\Users\yeyupiaoling/Python从入门到精通\test_files

目录相关操作

import os

# 获取当前工作目录
current_dir = os.getcwd()
print(f"当前工作目录: {current_dir}")

# 列出目录内容
print("目录内容:")
for item in os.listdir('.'):
    print(f"  {item}")

# 创建目录
test_dir = 'test_subdir'
if not os.path.exists(test_dir):
    os.mkdir(test_dir)
    print(f"创建目录: {test_dir}")
else:
    print(f"目录已存在: {test_dir}")

print(f"检查目录是否存在: {os.path.exists(test_dir)}")
print(f"是否为目录: {os.path.isdir(test_dir)}")

输出结果:

当前工作目录: C:\Users\yeyupiaoling/Python从入门到精通\test_files
目录内容: ['binary_sample.bin', 'numbers.txt', 'output.txt', 'sample.txt', 'test_dir_ops.py', 'test_file_ops.py']
创建目录: test_subdir
检查目录是否存在: True
是否为目录: True

路径操作

import os.path

# 路径拼接
file_path = os.path.join('test_subdir', 'test.txt')
print(f"拼接路径: {file_path}")
print(f"目录名: {os.path.dirname(file_path)}")
print(f"文件名: {os.path.basename(file_path)}")
print(f"分离路径: {os.path.split(file_path)}")
print(f"分离扩展名: {os.path.splitext(file_path)}")

输出结果:

拼接路径: test_subdir\test.txt
目录名: test_subdir
文件名: test.txt
分离路径: ('test_subdir', 'test.txt')
分离扩展名: ('test_subdir\\test', '.txt')

pathlib模块(Python 3.4+)

pathlib提供了面向对象的路径操作方式:

from pathlib import Path

# 创建Path对象
path = Path('.')
print(f"当前路径: {path.absolute()}")
print(f"路径是否存在: {path.exists()}")
print(f"是否为目录: {path.is_dir()}")

# 创建文件
test_file = Path('test_subdir') / 'pathlib_test.txt'
test_file.write_text('Hello from pathlib!', encoding='utf-8')
print(f"创建文件: {test_file}")
print(f"文件内容: {test_file.read_text(encoding='utf-8')}")

输出结果:

当前路径: C:\Users\yeyupiaoling/Python从入门到精通\test_files
路径是否存在: True
是否为目录: True
创建文件: test_subdir\pathlib_test.txt
文件内容: Hello from pathlib!

文件和目录的遍历

使用os.walk()函数
import os

# 使用os.walk()遍历目录
print("使用os.walk()遍历目录:")
for root, dirs, files in os.walk('.'):
    print(f"\n当前目录: {root}")
    print(f"子目录: {dirs}")
    print(f"文件: {files}")
    break  # 只显示第一个目录作为示例
使用glob模块
import glob

# 创建一些测试文件
test_extensions = ['.txt', '.py', '.md']
for ext in test_extensions:
    filename = f'test_files/demo{ext}'
    with open(filename, 'w') as f:
        f.write(f'这是一个{ext}文件')

print("\n使用glob模块查找文件:")

# 查找所有.txt文件
txt_files = glob.glob('test_files/*.txt')
print(f"所有.txt文件: {txt_files}")

# 查找所有文件
all_files = glob.glob('test_files/*')
print(f"所有文件: {len(all_files)} 个")

# 递归查找
all_txt_recursive = glob.glob('test_files/**/*.txt', recursive=True)
print(f"递归查找所有.txt文件: {all_txt_recursive}")

# 使用pathlib的glob
from pathlib import Path
path = Path('test_files')
py_files = list(path.glob('*.py'))
print(f"使用pathlib查找.py文件: {py_files}")

实际应用示例

def organize_files_by_extension(directory):
    """
    按文件扩展名组织文件

    Args:
        directory: 要组织的目录路径
    """
    from collections import defaultdict
    import os

    file_groups = defaultdict(list)

    # 遍历目录中的所有文件
    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)
        if os.path.isfile(filepath):
            _, ext = os.path.splitext(filename)
            ext = ext.lower() or 'no_extension'
            file_groups[ext].append(filename)

    # 显示结果
    print(f"\n目录 '{directory}' 中的文件分类:")
    for ext, files in file_groups.items():
        print(f"{ext}: {len(files)} 个文件")
        for file in files[:3]:  # 只显示前3个
            print(f"  - {file}")
        if len(files) > 3:
            print(f"  ... 还有 {len(files) - 3} 个文件")

# 使用文件组织功能
organize_files_by_extension('test_files')

总结

本章详细介绍了Python中目录操作的各个方面:

  1. os模块基础:掌握了os模块的基本功能,如获取当前目录、列出目录内容、创建目录等。

  2. 路径处理:学习了路径拼接、分离和检查等操作,以及os.path和pathlib模块的使用。

  3. 目录遍历:了解了使用os.walk()、glob模块和pathlib的glob方法进行目录和文件的遍历。

  4. 文件组织示例:通过一个实际示例展示了如何按文件扩展名对目录中的文件进行分类和管理。

通过这些技能,你可以有效地管理文件系统中的目录结构,处理各种文件组织和分类任务,为数据处理和项目管理提供有力支持。

Xiaoye